Pete
Pete

Reputation: 114

Python Beginners - Searching a text file for an array of text

I'm brand new to python. I have a text file full of strings. I want to see which of these multiple strings contain a set of keywords. I've managed to write this:

f = open('C:\\blah\\list.txt')
for line in f:
    if 'keyword' in line:
        print line

Which works great! Its just, I have a lot of keywords to search, so I imagine I want to get an array in there somehow but I've looked, and can't find out how to do this.

Thanks

Upvotes: 0

Views: 953

Answers (1)

eumiro
eumiro

Reputation: 212915

Are you searching for lines with all keywords included?

keywords = ['abc', 'def', 'ghi']

for line in f:
    if all(keyword in line for keyword in keywords):
        print line

or with any of them? In the latter case replace the all with any.

Upvotes: 4

Related Questions