我希望将一个单词列表与一个字符串匹配,并获得匹配的单词数量.
现在我有这个:
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")
Run Code Online (Sandbox Code Playgroud)
我当前的正则表达式将匹配前3个,但我想知道列表中words有多少单词与传递给的字符串相匹配search.如果没有re.compile为列表中的每个单词创建新内容,这是否可行?
还是有另一种方法可以实现同样的目的吗?
我想保持re.compile最小数量的原因是速度,因为在我的应用程序中我有多个单词列表和大约3500个字符串要搜索.
ste*_*ema 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")
Run Code Online (Sandbox Code Playgroud)
会导致
['blue']
['red']
['red','blue']
[]
如果您需要获得使用它们的匹配数量 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"))
Run Code Online (Sandbox Code Playgroud)
会导致
1
1
2
0