我正在尝试比较文件的字符串" formatted_words.txt"与另一个自定义文件" dictionary.txt"在输出中,我正在尝试打印文件" dictionary.txt" formatted_words file中出现的" formatted_words.txt" dictionary file中的单词。
from itertools import izip
with open("formatted_words.txt") as words_file:
with open("dictionary.txt") as dict_file:
all_strings = list(map(str.strip,dict_file))
for word in words_file:
for a_string in all_strings:
if word in a_string:
print a_string
然而,在输出中,文件的所有单词" formatted_words.txt"正在打印,虽然这个文件中的许多单词不在" dictionary.txt"。我不能使用任何内置的python字典。任何帮助都将不胜感激。
答案 0 :(得分:1)
使用集合:
with open('formatted_words.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)
因为交叉点为空而无法打印