ColeWorld
ColeWorld

Reputation: 279

Searching for specific keywords in text Python

Lets say without regex I want to print a line in some text containing 3 words but can't have one word... I assume it'd look something like this:

In this example, let body be a collection of text

keyword1 = 'blue'
keyword2 = 'bunny'
keyword3 = 'fluffy'
badkeyword = 'rabies'
for link in links:
    text = str(body)
    if keyword1 in text and keyword2 in text and keyword3 in text and badkeyword not in text:
        print("found line")
        print(line)

I would want this to print the line with "blue" "bunny" and "fluffy" but if that line happened to have "rabies" in it, skip it.

Upvotes: 0

Views: 87

Answers (1)

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48037

You may simplify your if condition using all():

keywords = (keyword1, keyword2, keyword3)
if all(word in text for word in keywords) and badkeyword not in text:
    # Do something

Upvotes: 2

Related Questions