Adrian_G
Adrian_G

Reputation: 163

Check for existence of at least one string in a list

I have code that checks whether there is at least one of the modal verbs in my word_list.

with open('Requirements_good.txt') as myfile:
    word_list=[word for line in myfile for word in line.split()]


with open('Badwords_modalverbs.txt') as file:
    modalv = 0
    for word in file.readlines():
        if word.strip() in word_list:
            modalv = 1
    if modalv == 1:
        print ("one of the words found")

But there must be an easier, more elegant way to solve this. What is the quickest way to check it?

And how would one check for the opposit?: print anything if none of the words are found

Upvotes: 3

Views: 69

Answers (1)

kaya3
kaya3

Reputation: 51053

First, make word_list a set instead of a list, so that it's efficient to test membership of it. Then, you can use the any function:

with open('Requirements_good.txt') as myfile:
    # set comprehension instead of list comprehension
    word_set = {word for line in myfile for word in line.split()}

with open('Badwords_modalverbs.txt') as file:
    if any(word.strip() in word_set for word in file):
        print("one of the words found")

This is more efficient because you're no longer searching a list to test membership, but also the any function won't keep searching after it finds one match. The file.readlines() function is also unnecessary here; for word in file iterates over the lines without creating a list first.

Upvotes: 8

Related Questions