我有两个文本文件,一个是这样的
dog
cat
fish
和另一个类似的文件
The cat ran
The fish swam
The parrot sang
我希望能够搜索第二个文本文件,并打印出包含第一个文本文件中的单词的行,例如,输出的结果将是
The cat ran
The fish swam
那像这样的东西呢。我们从第一个文件中提取关键词并存储起来,然后在阅读第二个文件时,我们在打印前参考它们。
# file1.txt
# dog
# cat
# fish
# file2.txt
# The cat ran
# The fish swam
# The parrot sang
# reading file1 and getting the keywords
with open("file1.txt") as f:
key_words = set(f.read().splitlines())
# reading file2 and iterating over all read lines
with open("file2.txt") as f:
all_lines = f.read().splitlines()
for line in all_lines:
if any(kw in line for kw in key_words): # if any of the word in key words is in line print it
print(line)