You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

对比用户输入与文本文件时,匹配后仅输出行剩余部分的问题求助

解决匹配后仅输出行剩余部分的问题

Hey Artūrs, let's break down why you're only getting the rest of the line after a match and fix it!

常见问题原因

Most likely, your code is accidentally slicing the string starting from the match position instead of outputting the entire line/flight entry. For example, if you're using line.find(user_input) and then taking line[match_index:], that'll only give you everything after the match—not the whole line.

解决方案示例(Python)

Let's walk through corrected code based on two possible scenarios:

场景1:每个航班是文本文件中的单独一行

If your file has one flight per line like this:

LATVIJA/RIGA | BOEING-45 | RIGA - MASKAVA | 20.02.2018 / 15:55 | R-126
LATVIJA/RIGA | BOEING-45 | RIGA - HELSINKI | 25.02.2018 / 15:55 | R-127

Use this code to match and print the full line:

user_input = input("Enter flight number (e.g., R-126): ").strip()

with open("flights.txt", "r") as flight_file:
    for line in flight_file:
        cleaned_line = line.strip()  # Remove extra newlines/spaces
        if user_input in cleaned_line:
            print(cleaned_line)  # Print the entire line, not a slice!

场景2:所有航班在同一行(如你的示例)

If your file has all flights in a single line separated by |, you'll first need to split the content into individual flight entries:

user_input = input("Enter flight number: ").strip()

with open("flights.txt", "r") as flight_file:
    # Read the entire content and split into fields
    all_content = flight_file.read().strip()
    fields = [field.strip() for field in all_content.split("|")]
    
    # Group fields into flights (each flight has 5 fields based on your example)
    flights = [fields[i:i+5] for i in range(0, len(fields), 5)]
    
    # Find and print the matching flight
    for flight in flights:
        if user_input in flight:
            print(" | ".join(flight))  # Reconstruct the full flight line

关键要点

  • Avoid slicing unless you specifically need part of the line. Always reference the full line/flight entry when you want to output everything.
  • If your file's formatting is non-standard (all entries in one line), make sure to split and group the content correctly before matching.

内容的提问来源于stack exchange,提问作者Artūrs Mēnesis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:13:32