我想将一个单词列表与一个字符串进行匹配,并获取匹配的单词数。
现在我有这个:
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 个,但我想找出 words
列表中有多少单词与传递给 search
的字符串匹配。这是否可能无需为列表中的每个单词创建一个新的re.compile
?
或者有其他方法可以达到同样的目的吗?
我想将 re.compile
的数量保持在最低限度的原因是速度,因为在我的应用程序中我有多个单词列表和大约 3500 个要搜索的字符串反对。
最佳答案
如果您使用 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")
会导致
['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"))
将导致
1
1
2
0
关于Python RegEx,匹配字符串中的单词并获取计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7345252/