In Python, searching a text file for multiple words and printing the corresponding lines

I have a list of sentences I would like to search. I want to print the lines that contain my search words. This code works:

fruit_list = open('fruitlist.txt')
for line in fruit_list:
    if 'apple' in line or 'banana' in line or 'orange' in line:
        print (line)

But this can be pretty tedious; especially if I want my list of search words to be longer. I would like to make a list of search words and use that to search the document and print the line.

search_words=['apple','banana','orange','lemon']
for line in fruit_list:
    if item in search_words in line:
        print (line)

This code doesn't work because "item" isn't defined. Anyway I could get this done? I'm a newbie with python.

2 answers

  • answered 2018-07-12 05:22 Ashish Acharya

    Try this:

    fruit_list = open('fruitlist.txt')
    
    search_words = ['apple', 'banana', 'orange', 'lemon']
    
    for line in fruit_list:
        if any(word in line for word in search_words):
            print(line)
    

  • answered 2018-07-12 07:08 Ravinder Karra

    # with Regular Expression 
    import re
    
    fruit_list = open('test.txt')
    search_words = ['apple', 'banana', 'orange', 'lemon']
    
    patten = re.compile("(.*(apple|banana|orange|lemon)(.*))")
    
    for i in [re.search(patten,line).groups() for line  in      fruit_list  if re.search(patten,line) != None]: print(i)