我想用字符串匹配单词列表并获取多少个单词匹配。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字符串搜索对抗。
'当w在searchterm'将无法正常工作,因为还在'searchterm'匹配一个单词的一部分 – fredrik