【问题标题】:how to compare difference in 2 txt files and output to a new txt file如何比较 2 个 txt 文件的差异并输出到新的 txt 文件
【发布时间】:2021-10-23 03:36:58
【问题描述】:

如何比较两个txt文件的差异并输出并打印到shell?

此链接中的工作文件

【问题讨论】:

  • 显而易见的答案是忘记编写任何代码并使用执行此任务的数十种工具之一:diffmeldvimdiff 等。

标签: atom-editor


【解决方案1】:

在 Pandas 中使用drop_duplicates

df1 = pd.read_csv('members_1.txt', header=None).drop_duplicates()
df2 = pd.read_csv('members_2.txt', header=None).drop_duplicates()
out = pd.concat([df1, df2]).drop_duplicates(keep=False)

输出

>> print(*out[0].to_list(), sep='\n')
LEE RI KE
LIM YONG
KOH CHEE KIAT
LEE YONG
KOH CHEW KIAT
LEE RI KHEE

在 Python 中使用set

with open('members_1.txt') as fp1, open('members_2.txt') as fp2:
    data1 = set([l.strip() for l in fp1])
    data2 = set([l.strip() for l in fp2])
    out = data1.symmetric_difference(data2)

输出:

>>> print(*out, sep='\n')
KOH CHEW KIAT
LEE RI KE
LEE YONG
KOH CHEE KIAT
LEE RI KHEE
LIM YONG

更新:导出到文件

with open('output.txt', 'w') as fp:
    print(*out, sep='\n', file=fp)

【讨论】:

  • 我尝试使用 output.savetxt() 但它不起作用,我的语法是否正确? @Corralien
  • 我更新了我的答案。符合你的预期吗?
  • SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: malformed \N character escape, 我得到那个错误,我必须先创建文件吗?
  • 为什么是 '\N' 而不是 '\n'?
  • 我的错误目录...
【解决方案2】:

当然用diff

difflib.Differ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2018-01-09
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多