如何用Python实现根据文本文件中相似数字匹配输出对应字母?
Solution
Here's the completed code that implements your desired logic, along with a breakdown of how it works:
import re # Define the target numbers we're searching for (as strings to match split line elements) TARGET_1 = '12389390' TARGET_2 = '34789021' # Initialize lists to hold letters for each target group group_target1 = [] group_target2 = [] # Process the input text file with open('letter.txt', 'r') as file: for line in file: stripped_line = line.strip() # Skip empty lines to avoid errors if not stripped_line: continue # Only process lines starting with a letter (matches your original check) if re.match('^[a-zA-Z]+', stripped_line): parts = stripped_line.split() letter = parts[0] # Add letter to group 1 if target 1 is present in the line if TARGET_1 in parts: group_target1.append(letter) # Add letter to group 2 if target 2 is present in the line if TARGET_2 in parts: group_target2.append(letter) # Combine the groups: first all letters with target 1, then all with target 2 result = group_target1 + group_target2 output_str = ' '.join(result) # Print the final output (matches your expected result) print(output_str) # Outputs: A C E B D E # Write the result to the CSV file with open('letter.csv', 'a+') as output: # Add a newline to keep entries separate on subsequent runs output.write(output_str + '\n')
Key Details & Explanation:
- Target Matching: We use string checks because splitting each line turns all elements into strings, making direct comparisons straightforward.
- Group Separation: By using two lists, we maintain the order of lines from the input file while separating letters based on which target they contain.
- Dual Target Handling: Lines that contain both targets (like line E) are added to both groups, so they appear twice in the final result.
- Clean File Handling: We strip whitespace and skip empty lines to avoid processing invalid entries, and append a newline to the CSV file to keep entries formatted properly.
Note: Based on your input text, the code produces A C E B D E (with E appearing twice, once for each target). If your expected output of A C E B D E E was a typo, this code aligns perfectly with your described logic. If you intended an extra E, you'd need to adjust the logic to account for multiple occurrences of a target in a single line (though your input doesn't show this).
内容的提问来源于stack exchange,提问作者jan
相关产品推荐
相关产品推荐

