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

如何对比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的行),完全搞反了基准文件的遍历方向
  • 只收集了不匹配的行,没有保留所有行并添加要求的匹配标注
  • 没有按照预期格式输出每行的标注文本

修正后的代码要点:

  1. 将eg1的内容存入集合,集合的成员查找速度比列表快很多,适合做这类匹配检查
  2. 遍历eg2的每一行(符合「以eg2为基准」的要求)
  3. 对每行判断是否存在于eg1的集合中,拼接对应的标注文本
  4. 最后将所有带标注的行写入out.txt,同时保留换行格式

内容的提问来源于stack exchange,提问作者V_S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:45:43