Python RegEx,匹配字符串中的单词并获取计数

标签 python regex

我想将一个单词列表与一个字符串进行匹配,并获取匹配的单词数。

现在我有这个:

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/

相关文章:

python - 用python比较2个日期

php - 在 PHP 中捕获重复字母 - 正则表达式

javascript - 正则表达式匹配模式以 ':' 结尾但不包含它

正则表达式捕获两个数字之间的第一个字符串

python - 在 os.listdir(path) 中使用文件扩展名通配符

python - AttributeError: 图片没有属性 'open'

python - 如何根据其他列 'Applicant_Income' 的条件绘制列 'Education"的直方图?

关于花费时间的Python问题

regex - VIM:根据位置插入或删除数据

Javascript 书签无响应