Python:计算 2 个文件之间的 uniq 行


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

使用下面的代码,我得到输出:鲍,但我需要得到鲍勃 x 2

with open('some_file_1.txt', 'r') as file1:
     with open('some_file_2.txt', 'r') as file2:
         diff = set(file1).difference(file2)
 with open('some_output_file.txt', 'w') as file_out:
     for line in same:
        file_out.write(line)

听起来你想要两个collections.Counter对象的差异。

import collections
with open("file1.txt") as f1, open("file2.txt") as f2:
    c1, c2 = collections.Counter(f1), collections.Counter(f2)
    result = c1 - c2
    # Counter({"bob": 2})
with open("output.txt", "w") as outf:
    for line, count in result.items():
        outf.write("{} x {}".format(line, count))

最新更新