如何对比eg1.txt与eg2.txt并生成带匹配标记的out.txt?
问题修正方案
你的代码逻辑完全搞反了,而且没有实现每行添加匹配标注的需求,以下是修正后的代码:
# 先读取eg1的内容,转成集合提升查找效率 with open("eg1.txt", "r") as f: eg1_lines = {line.strip() for line in f.readlines()} # 以eg2为基准遍历每行,生成带标注的内容 output_lines = [] with open("eg2.txt", "r") as f: for line in f.readlines(): stripped_line = line.strip() if stripped_line in eg1_lines: output_lines.append(f'{stripped_line} "Matching with eg1.txt"') else: output_lines.append(f'{stripped_line} "Not Matching with eg1.txt"') # 写入输出文件 with open("out.txt", "w") as f: f.write('\n'.join(output_lines) + '\n') print("输出文件已生成:") print('\n'.join(output_lines))
原代码的问题说明:
- 变量逻辑混乱:你把eg2的内容存在
file_1,eg1的存在file_2,但循环遍历的是file_2(也就是eg1的行),完全搞反了基准文件的遍历方向 - 只收集了不匹配的行,没有保留所有行并添加要求的匹配标注
- 没有按照预期格式输出每行的标注文本
修正后的代码要点:
- 将eg1的内容存入集合,集合的成员查找速度比列表快很多,适合做这类匹配检查
- 遍历eg2的每一行(符合「以eg2为基准」的要求)
- 对每行判断是否存在于eg1的集合中,拼接对应的标注文本
- 最后将所有带标注的行写入out.txt,同时保留换行格式
内容的提问来源于stack exchange,提问作者V_S
相关产品推荐
相关产品推荐

