Python:如何检查文本文件中是否存在两个或多个给定单词

Python: How check if two or more given words are present in a text file

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

例如,如果文件包含 Q1、Q2、Q3、Q4 但不是 Q5 它应该输出为 "Q5 not found" 或至少 "not all questions found"

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

这是一种方法:

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

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

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

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