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

时间:2017-08-06 11:50:32

标签: 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 '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”期望单个字符串,而不是列表。对于这样的事情,什么是有价值的解决方案?

谢谢。

3 个答案:

答案 0 :(得分:2)

如果您不想编写多个if-else语句,可以创建一个const fun = function(){ var promise = new Promise(resolve => { setTimeout(resolve, 2000); }) for(var i=0; i<1000; i++){ promise.then(() => console.log(i)); } } 来存储要作为键搜索的字符串,以及作为值执行的函数。

例如

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() 之类的:

log.txt

输出

string_1
string_2
string_1

答案 1 :(得分:0)

循环你的字符串列表,而不是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 :(得分: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
相关问题