比较 Python 中的两个文本文件

Compare two txt files in Python

我有两个输入文件:

one.txt: 一种 一种 一种 一种 一种 b b b b b

two.txt b b b C b 一种 一种 C 一种 一种 b

我有以下代码:

with open('two.txt', 'r') as file1:
    with open('one.txt', 'r') as file2:
        difference = set(file1).difference(file2)

difference.discard('\n')

with open('difff.txt', 'w') as file_out:
    for line in difference:
        file_out.write(line)

我得到的输出为:

c

但我想要这样的东西:

c

c

有人可以帮我解决这个问题吗?

使用collections.Counter:

with open('one.txt') as f1, open('two.txt') as f2:
    one = Counter(f1.read().split())
    two = Counter(f2.read().split())

with open('diff.txt', 'w') as outfile:
    for c, i in (two - one).items():
        outfile.write(f'{c}\n' * i)