打印两个文本文件中常用的单词

时间:2017-11-22 23:47:22

标签: python-3.x python-2.7

我有两个名为dictionary.txt file_dictionary和output.txt file_output的文本文件。这两个文件都有三个常用的单词dance,sanct和test但我没有得到任何单词返回比较两个文件:

with open('output.txt') as words_file:
with open('dictionary.txt') as dict_file:
    all_strings = set(map(str.strip, dict_file))
    words = set(map(str.strip, words_file))
    for word in all_strings.intersection(words):
        print(word) 

我无法解决问题。请帮助!

1 个答案:

答案 0 :(得分:0)

Python字符串区分大小写。 output.txt中的字符串是大写字母,因此您需要在进行比较之前将它们转换为小写:

# remove set from this line
words = map(str.strip, words_file)   

# convert list to lower-case, then apply set operation
words = set(map(str.lower, words))

# everything else same as before
for word in all_strings.intersection(words):
       ...

输出:

dance
test
sanct