【发布时间】:2020-07-01 23:37:00
【问题描述】:
我尝试编写一个 python 函数来计算字符串中的特定单词。
当我要计算的单词连续重复多次时,我的正则表达式模式不起作用。否则,该模式似乎运作良好。
这是我的功能
import re
def word_count(word, text):
return len(re.findall('(^|\s|\b)'+re.escape(word)+'(\,|\s|\b|\.|$)', text, re.IGNORECASE))
当我用随机字符串测试它时
>>> word_count('Linux', "Linux, Word, Linux")
2
当我要数的词与自己相邻时
>>> word_count('Linux', "Linux Linux")
1
【问题讨论】:
-
请注意,
'\b'是退格字符,'\x08',而不是'\\b'