比较两个文件以打印与单词匹配的行

2024-06-16 09:51:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个文本文件,一个像这样

dog cat fish

还有一个像这样的文件

The cat ran The fish swam The parrot sang

我希望能够搜索第二个文本文件并打印包含第一个文本文件中的单词的行,例如,此文件的输出为

The cat ran The fish swam


Tags: 文件the单词catparrot文本文件dogfish
1条回答
网友
1楼 · 发布于 2024-06-16 09:51:28

像这样的怎么样。我们从第一个文件中提取关键字并存储它们,然后在阅读第二个文件时在打印之前引用它们

# 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)

相关问题 更多 >