【问题标题】:Python: How check if two or more given words are present in a text filePython:如何检查文本文件中是否存在两个或多个给定单词
【发布时间】:2019-01-29 12:35:56
【问题描述】:

我有一个文本文件考虑 questions.txt,我想检查所有 5 个问题编号是否都存在

例如,如果文件包含 Q1、Q2、Q3、Q4 但不是 Q5,它应该输出为“Q5 not found” 或至少作为“未找到所有问题”

基本上我想搜索txt文件中是否存在所有给定的单词(问题编号)

【问题讨论】:

  • 问题的定义是什么?我假设您的文件不只是包含字面上的“Q1、Q2、Q3、Q4”?
  • @FynnBecker 是的,就像第 1 行-“Q1 : blah blah”第 2-“Q2 : blah blah”...等

标签: python python-3.x python-requests python-import text-processing


【解决方案1】:

这是一种方法:

WORDS_TO_FIND = tuple("Q{}".format(i) for i in range(5))

with open('questions.txt') as file:
    text = file.read()
    for word in WORDS_TO_FIND:
        if word not in text:
            print("{} not found".format(word))

对于更复杂的模式,您也可以使用re.search()。

【讨论】:

    【解决方案2】:

    考虑到变量 text 作为您要搜索的 text,我会使用:

    oc_Q = re.findall(r'[Q][1-5]', text)
    print (oc_Q)
    

    oc_Q 将包含所有出现的 Q[1-5]。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-16
      • 1970-01-01
      • 2012-11-09
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多