对比用户输入与文本文件时,匹配后仅输出行剩余部分的问题求助
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

