Python 使用字符串列表搜索文件中的多个字符串

Python 使用字符串列表搜索文件中的多个字符串,python,string,python-2.7,list,search,Python,String,Python 2.7,List,Search,我试图以某种方式搜索多个字符串,并在找到某个字符串时执行某个操作。 是否可以提供字符串列表并在文件中搜索该列表中存在的任何字符串 list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3'] 我现在一个接一个地做,在一个新的if-elif-else语句中指出我要搜索的每个字符串,如下所示: with open(logPath) as file: for line in file: if 'str

我试图以某种方式搜索多个字符串,并在找到某个字符串时执行某个操作。 是否可以提供字符串列表并在文件中搜索该列表中存在的任何字符串

list_of_strings_to_search_for = ['string_1', 'string_2', 'string_3']
我现在一个接一个地做,在一个新的if-elif-else语句中指出我要搜索的每个字符串,如下所示:

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
我已经尝试过传递列表本身,但是,“if x in line”需要一个字符串,而不是列表。对于这样的事情,什么是值得的解决方案


谢谢。

循环字符串列表,而不是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))

如果不想编写几个If-else语句,可以创建一个
dict
,将要搜索的字符串存储为键,将要执行的函数存储为值

例如

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()
hello
hi
hello
使用类似以下内容的
log.txt

string_1
string_2
string_1
输出为

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()
hello
hi
hello

下面是一种使用Python附带的正则表达式re模块的方法:

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())
打印出:

A at 8
B at 25
C at 51

您是否尝试匹配单词,例如“hello”和“world”都在“hello world”中找到,但没有找到“o”,或者“o”会被找到两次,因为您需要简单的子字符串匹配?@JohnZwinck嘿John,我要查找的字符串(例如,字符串_1)在我的日志文件中是显式的,所以这对我来说并不重要。我将搜索一个只能找到一次的字符串。太好了,这正是我要找的。我对它做了一些修改以满足我的需要,因为我不想创建更多的函数。我的版本很快会在原始帖子中更新。非常感谢你,里卡多!我很高兴这有帮助!