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

时间:2016-01-29 00:25:15

标签: python text-files counter

atomic_int

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

 First File | Second File

    bob        | greg
    bob        | larry
    mark       | mark
    larry      | bruce
    tom        | tom

1 个答案:

答案 0 :(得分:2)

听起来你想要两个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))