Search multiple lines in a file using a list of lines

I am trying to search for multiple lines in some way and perform a specific action when a specific line is found. Is it possible to provide a list of strings and go through a file looking for any strings that are present in that list?

list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3']

      

Currently I am doing this one by one, specifying each line I want to find in a new if-elif-else statement, like this:

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 tried to pass in the list itself, however "if x in line" expects a single line, not a list. What is a decent solution for such a thing?

Thank.

+3


source to share


3 answers


If you don't want to write multiple if-else statements, you can create dict

one that stores the strings you want to search for as keys and functions that are executed 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 log.txt

how:



string_1
string_2
string_1

      

Conclusion :

hello
hi
hello

      

+2


source


loop your list of strings, not 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))

      

0


source


Here's one way to do it using the re regular expressions included in 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())

      

gives out:

A at 8
B at 25
C at 51

      

0


source







All Articles