2011-08-02 76 views
2

如何在搜索列表時匹配精確的字符串/詞。我試過了,但它不正確。下面我給了sample listmy codetest results搜索列表:僅匹配精確的詞/字符串

 
list = ['Hi, hello', 'hi mr 12345', 'welcome sir'] 

我的代碼:

 
for str in list: 
    if s in str: 
    print str 

測試結果:

 
s = "hello" ~ expected output: 'Hi, hello' ~ output I get: 'Hi, hello' 
s = "123" ~ expected output: *nothing* ~ output I get: 'hi mr 12345' 
s = "12345" ~ expected output: 'hi mr 12345' ~ output I get: 'hi mr 12345' 
s = "come" ~ expected output: *nothing* ~ output I get: 'welcome sir' 
s = "welcome" ~ expected output: 'welcome sir' ~ output I get: 'welcome sir' 
s = "welcome sir" ~ expected output: 'welcome sir' ~ output I get: 'welcome sir' 

我的目錄包含超過200K串

+0

正則表達式? – Gandi

回答

1

看起來你不僅需要執行一次此搜索,所以我會推薦給你的列表轉換成詞典:

>>> l = ['Hi, hello', 'hi mr 12345', 'welcome sir'] 
>>> d = dict() 
>>> for item in l: 
...  for word in item.split(): 
...    d.setdefault(word, list()).append(item) 
... 

所以現在你可以很容易做到:

>>> d.get('hi') 
['hi mr 12345'] 
>>> d.get('come') # nothing 
>>> d.get('welcome') 
['welcome sir'] 

PS可能你必須改進item.split()以處理逗號,點和其他分隔符。也許使用正則表達式和\w

p.p.s.因爲cularion提到這不符合「歡迎先生」。如果你想匹配整個字符串,它只是提出解決方案的一條附加線。但如果你必須匹配由空格和標點符號regex的字符串部分應該是你的選擇。

+1

哦,我的,爲什麼這麼複雜? –

0

如果您搜索完全匹配:

for str in list: 
    if set (s.split()) & set(str.split()): 
    print str 
0

提供s永遠只能由短短的幾句話,你可以做

s = s.split() 
n = len(s) 
for x in my_list: 
    words = x.split() 
    if s in (words[i:i+n] for i in range(len(words) - n + 1)): 
     print x 

如果s包括很多的話,也有更有效,但也更復雜的算法來此。這裏

0
>>> l = ['Hi, hello', 'hi mr 12345', 'welcome sir'] 
>>> search = lambda word: filter(lambda x: word in x.split(),l) 
>>> search('123') 
[] 
>>> search('12345') 
['hi mr 12345'] 
>>> search('hello') 
['Hi, hello'] 
0

使用正則表達式來精確字與字邊界\ B匹配

import re 
..... 
for str in list: 
if re.search(r'\b'+wordToLook+'\b', str): 
    print str 

\僅b,其被終止,並且用字開頭的單詞匹配終止子例如空格或換行符

或者做這樣的事情,以避免一次又一次地搜索單詞。

import re 
list = ['Hi, hello', 'hi mr 12345', 'welcome sir'] 
listOfWords = ['hello', 'Mr', '123'] 
reg = re.compile(r'(?i)\b(?:%s)\b' % '|'.join(listOfWords)) 
for str in list: 
    if reg.search(str): 
     print str 

(我)是搜索,而不用擔心文字的情況下,如果你想用大小寫進行搜索,然後將其刪除。