【问题标题】:Comparing two files to print a line that matches a word比较两个文件以打印与单词匹配的行
【发布时间】:2020-04-24 14:59:00
【问题描述】:

我有两个这样的文本文件

dog cat fish

还有一个这样的文件

The cat ran The fish swam The parrot sang

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

The cat ran The fish swam

【问题讨论】:

  • 你必须展示你到目前为止所做的事情。仅仅说出你的目标是不够的。
  • 您应该共享代码或至少共享您计划使用的方法。在帮助您的过程中,可能有一些我们可能不知道的未知数。提示:如果第一个文件只包含单词,请将它们保存在 set
  • 建议在发布问题之前搜索现有的解决方案,这个似乎相似 -*.com/questions/33103648/…
  • 请展示你到目前为止所做的尝试

标签: python python-3.x search text printing


【解决方案1】:

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

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

【讨论】:

  • 非常感谢,你不知道我盯着这个简单的问题看了多久
  • 没问题,乐于助人。
  • 这将随着文件的大小而爆炸