Reputation: 153
I am attempting to somehow search for multiple strings and perform a certain action when a certain string is found. Is it possible to provide a list of strings and go through the file searching for any of the strings that are present in that list?
list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3']
I'm currently doing it one-by-one, indicating every string I want to search for in a new if-elif-else statement, like so:
with open(logPath) as file:
for line in file:
if 'string_1' in line:
#do_something_1
elif 'string_2' in line:
#do_something_2
elif 'string_3' in line:
#do_something_3
else:
return True
I have tried passing the list itself, however, the "if x in line" is expecting a single string, and not a list. What is a worthy solution for such a thing?
Thank you.
Upvotes: 3
Views: 6535
Reputation: 1332
Here is one way to do it with the regular expressions re module included with Python:
import re
def actionA(position):
print 'A at', position
def actionB(position):
print 'B at', position
def actionC(position):
print 'C at', position
textData = 'Just an alpha example of a beta text that turns into gamma'
stringsAndActions = {'alpha':actionA, 'beta':actionB ,'gamma':actionC}
regexSearchString = str.join('|', stringsAndActions.keys())
for match in re.finditer(regexSearchString, textData):
stringsAndActions[match.group()](match.start())
prints out:
A at 8
B at 25
C at 51
Upvotes: 0
Reputation: 597
If you don't want to write several if-else statements, you can create a dict
that stores the strings you want to search as keys, and the functions to execute as values.
For example:
logPath = "log.txt"
def action1():
print("Hi")
def action2():
print("Hello")
strings = {'string_1': action1, 'string_2': action2}
with open(logPath, 'r') as file:
for line in file:
for search, action in strings.items():
if search in line:
action()
With a log.txt
like:
string_1
string_2
string_1
The ouput is:
hello
hi
hello
Upvotes: 3
Reputation: 432
loop your string list, instead of if/else
list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3']
with open(logPath) as file:
for line in file:
for s in list_of_strings_to_search_for:
if s in line:
#do something
print("%s is matched in %s" % (s,line))
Upvotes: 2