两个文本文件之间的差异和交集报告

2024-05-20 02:32:06 发布

您现在位置:Python中文网/ 问答频道 /正文

免责声明:我对编程和脚本一般来说都是新手,因此请原谅缺少技术术语

因此,我有两个文本文件数据集,其中包含列出的名称:

First File | Second File
bob        | bob
mark       | mark
larry      | bruce
tom        | tom

我想运行一个脚本(pref python),它输出一个文本文件中的交线和另一个文本文件中的不同行,例如:

匹配.txt

bob 
mark 
tom 

差异.txt

bruce

我如何用Python来实现这一点?或者使用Unix命令行,如果它足够简单的话?


Tags: 数据txt脚本名称声明编程技术file
3条回答
words1 = set(open("some1.txt").read().split())
words2 = set(open("some2.txt").read().split())

duplicates  = words1.intersection(words2)
uniques = words1.difference(words2).union(words2.difference(words1))

print "Duplicates(%d):%s"%(len(duplicates),duplicates)
print "\nUniques(%d):%s"%(len(uniques),uniques)

至少是这样

Unix外壳解决方案-:

# duplicate lines
sort text1.txt text2.txt | uniq -d

# unique lines
sort text1.txt text2.txt | uniq -u

sort | uniq很好,但comm可能更好。”更多信息。

从手册页:

EXAMPLES
       comm -12 file1 file2
              Print only lines present in both file1 and file2.

       comm -3 file1 file2
              Print lines in file1 not in file2, and vice versa.

您也可以使用Python set类型,但是comm更容易。

相关问题 更多 >