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

3

我正尝试搜索多个字符串,并在找到某个特定字符串时执行某个操作。 是否可以提供一个字符串列表并遍历文件以搜索列表中存在的任何字符串?

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”需要一个单独的字符串而不是一个列表。针对这种情况有什么好的解决方案呢?

谢谢。


你是想匹配单词吗,比如"hello"和"world"都在"hello world"中找到了,但是"o"没有找到,还是"o"会被找到两次,因为你想要简单的子字符串匹配? - John Zwinck
@JohnZwinck 嘿,John,我正在寻找的字符串(例如,string_1)在我的日志文件中是明确的,所以对我来说并不重要。我将搜索只能找到一次的字符串。 - Kfir Cohen
3个回答

2

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

2
如果你不想写多个if-else语句,可以创建一个字典来存储你想要搜索的字符串作为键,并将要执行的函数作为值。
例如:
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()

有一个名为log.txt的文件:

string_1
string_2
string_1

输出结果为:

hello
hi
hello

1
完美,这正是我在寻找的。我稍微修改了一下以适应我的需求,因为我不想创建更多的函数。我的版本很快会更新到原始帖子中。非常感谢你,Ricardo! - Kfir Cohen
我很高兴它能帮到你! - Ricardo

0
这是一个使用 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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接