简体   繁体   中英

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

I have a text file consider questions.txt, I wanted to check if all the 5 questions numbers are present or not

For example, if the file contains Q1, Q2, Q3, Q4 But not Q5 it should output as "Q5 not found" or atleast as "not all questions found"

Basically I wanted to search if all the given words(question numbers)are present in the txt file or not

Here is one way to do that:

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

You could also use re.search() for more complicated patterns.

Considering the variable text as the text you'd like to search, I'd use:

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

oc_Q will contain all occurrences of the Q[1-5]s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM