2017-08-06 117 views
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」期望單個字符串,而不是列表。什麼是這樣的事情的有價值的解決方案?

謝謝。

+0

你是不是想匹配的話,如 「你好」 和 「世界」 都在 「Hello World」 的發現,但「o」沒有找到,或者「o」會被找到兩次,因爲你想要簡單的子串匹配? –

+0

@JohnZwinck嘿約翰,我正在尋找的字符串(例如,string_1)在我的日誌文件中是顯式的,所以它對我來說並不重要。我將搜索只能找到一次的字符串。 –

回答

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 
+1

完美,這正是我所尋找的。我已經改變了一下以適應我的需求,因爲我不想創建更多的功能。我的這個版本將很快在原文中更新。非常感謝里卡多! –

+0

我很高興它幫助! – Ricardo

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)) 
0

這裏是用做的一種方式單組LAR表達重新模塊包括在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()) 

打印出:

A at 8 
B at 25 
C at 51