Python 比较两个文本文件(顺序无关紧要),并将两个文件共有的单词输出到第三个文件

Python 比较两个文本文件(顺序无关紧要),并将两个文件共有的单词输出到第三个文件,python,Python,我刚开始编程,我正在尝试比较两个文件,如下所示: file1: tootsie roll apple in the evening file2: hello world do something apple output: "Apple appears x times in file 1 and file 2" 我真的被难倒了。我尝试过创建字典、列表、元组、集合,但似乎无法获得所需的输出。我得到的最接近的结果是输出的行与file1/file2的输出完全相同 我在这里尝试了几段代码,但似乎都

我刚开始编程,我正在尝试比较两个文件,如下所示:

file1:
tootsie roll
apple
in the evening

file2:
hello world
do something
apple

output:
"Apple appears x times in file 1 and file 2"
我真的被难倒了。我尝试过创建字典、列表、元组、集合,但似乎无法获得所需的输出。我得到的最接近的结果是输出的行与file1/file2的输出完全相同

我在这里尝试了几段代码,但似乎都无法输出我想要的内容。任何帮助都将不胜感激

这是我尝试的最后一段代码,它没有给我第三个文件任何输出

f1 = open("C:\\Users\\Cory\\Desktop\\try.txt", 'r')
f2 = open("C:\\Users\\Cory\\Desktop\\match.txt", 'r')
output = open("C:\\Users\\Cory\\Desktop\\output.txt", 'w')

file1 = set(f1)
file2 = set(f2)
file(word,freq)
for line in f2:
    word, freq = line.split()
    if word in words:
        output.write("Both files have the following words: " + file1.intersection(file2))
f1.close()
f2.close()
output.close()

您不需要所有这些循环—如果文件很小(即小于几百MB),您可以更直接地使用它们:

words1 = f1.read().split()
words2 = f2.read().split()
words = set(words1) & set(words2)
words
将是一个
集合
,包含这些文件共有的所有单词。在拆分文本之前,可以使用
lower()
忽略大小写

要对注释中提到的每个单词进行计数,只需使用
count()
方法:

with open('outfile.txt', 'w') as output:
    for word in words:
        output.write('{} appears {} times in f1 and {} times in f2.\n'.format(word, words1.count(word), words2.count(word))

你到底想要什么输出?我想让我的第三个文件有一个匹配文件中每个单词的输出(例如,如果苹果在文件1中的任何位置,苹果在文件2中的任何位置,我会得到一个苹果的输出:x(x=苹果在两个文件中出现的次数),然后我想知道两个文件中有多少个单词。