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_lis
Solution 1:
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)
Solution 2:
# 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)
Post a Comment for "In Python, Searching A Text File For Multiple Words And Printing The Corresponding Lines"