【问题标题】:Searching for multiple strings in a file by using a list of strings使用字符串列表在文件中搜索多个字符串
【发布时间】:2018-01-13 20:44:47
【问题描述】:

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

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"简单的子串匹配?
  • @JohnZwinck 嘿,约翰,我正在寻找的字符串(例如,string_1)在我的日志文件中是明确的,所以这对我来说并不重要。我将搜索一个只能找到一次的字符串。

标签: python string python-2.7 list search


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果您不想编写多个 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()
    

    log.txt 喜欢:

    string_1
    string_2
    string_1
    

    输出是

    hello
    hi
    hello
    

    【讨论】:

    • 完美,这正是我想要的。我对其进行了一些更改以满足我的需要,因为我不想创建更多功能。我的这个版本很快就会在原帖中更新。非常感谢里卡多!
    • 我很高兴它有帮助!
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-30
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 1970-01-01
      相关资源
      最近更新 更多