2011-09-08 206 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 

,如果你想测试多种颜色,您需要更多的代码

相关问题