Python 正则表达式,匹配字符串中的单词并获取计数

2 投票
4 回答
14944 浏览
提问于 2025-04-17 01:46

我想把一堆单词和一个字符串进行匹配,看看有多少个单词是匹配的。

现在我有这个:

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")

我现在的正则表达式可以匹配前面三个单词,但我想知道在列表 words 中有多少个单词能和传入的 search 字符串匹配。有没有办法为列表中的每个单词都创建一个新的 re.compile 呢?

或者有没有其他方法可以实现同样的效果?

我想尽量减少 re.compile 的数量是因为速度,因为在我的应用中,我有多个单词列表和大约3500个字符串需要进行匹配。

4 个回答

1
for w in words:
    if w in searchterm:
        print "found"

当然可以!请把你想要翻译的内容发给我,我会帮你把它变得简单易懂。

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

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

11

如果你用 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

撰写回答