3

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.

2
  • Are you trying to match words, like "hello" and "world" are both found in "hello world" but "o" is not found, or would "o" be found twice because you want simple substring matching? Commented Aug 6, 2017 at 12:01
  • @JohnZwinck Hey John, the strings I am looking for (for example, string_1) are explicit in my log file, so it doesn't really matter to me. I will be searching for a string which can only be found once. Commented Aug 6, 2017 at 12:08

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect, This is exactly what I was looking for. I have changed it a bit to suit my needs, as I did not want to create more functions. My version of this will soon be updated in the original post. Thank you very much Ricardo!
I'm glad it helped!
2

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))

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.