2011-09-08 209 views
2

我想用字符串匹配單詞列表並獲取多少個單詞匹配。Python正則表達式,匹配字符串中的字符並獲得計數

現在我有這樣的:

import re 
words = ["red", "blue"] 
exactMatch = re.compile(r'\b%s\b' % '\\b|\\b'.join(words), flags=re.IGNORECASE) 
print exactMatch.search("my blue cat") 
print exactMatch.search("my red car") 
print exactMatch.search("my red and blue monkey") 
print exactMatch.search("my yellow dog") 

我現在的正則表達式將匹配前3,但我想找出多少的傳遞給search匹配字符串列表words的話。這可能是沒有爲列表中的每個單詞創建一個新的re.compile

或者還有另外一種方法可以達到同樣的效果嗎?

我想要的re.compile數量保持在最低水平的原因是速度,因爲在我的應用程序有多個單詞列表,並約3500字符串搜索對抗。

回答

10

如果使用findall,而不是search,那麼你得到包含一個元組作爲結果所有匹配的單詞。

print exactMatch.findall("my blue cat") 
print exactMatch.findall("my red car") 
print exactMatch.findall("my red and blue monkey") 
print exactMatch.findall("my yellow dog") 

將導致

[ '藍色']
[ '紅']
[ '紅', '藍']
[]

如果您需要獲得您使用的匹配數量len()

print len(exactMatch.findall("my blue cat")) 
print len(exactMatch.findall("my red car")) 
print len(exactMatch.findall("my red and blue monkey")) 
print len(exactMatch.findall("my yellow dog")) 

將導致

1

爲什麼不存儲在哈希的所有文字和遍歷每個單詞的句子中查找通一finditer

words = { "red": 1 .... } 
    word = re.compile(r'\b(\w+)\b') 
    for i in word.finditer(sentence): 
    if words.get(i.group(1)): 
     .... 
1
for w in words: 
    if w in searchterm: 
     print "found" 
+0

'當w在searchterm'將無法正常工作,因爲還在'searchterm'匹配一個單詞的一部分 – fredrik

3

如果我得到了正確的問題,你只需要知道的藍色或紅色的匹配的數量一句話。

>>> exactMatch = re.compile(r'%s' % '|'.join(words), flags=re.IGNORECASE) 
>>> print exactMatch.findall("my blue blue cat") 
['blue', 'blue'] 
>>> print len(exactMatch.findall("my blue blue cat")) 
2 

,如果你想測試多種顏色,您需要更多的代碼

相關問題