Skip to main content
 首页 » 编程设计

python之没有空格和特殊字符的字符串中的词频

2024年11月01日24arxive

假设我有以下字符串:

"hello&^uevfehello!`.<hellohow*howdhAreyou" 

我将如何计算作为它的子字符串的英语单词的频率?在这种情况下,我想要这样的结果:

{'hello': 3, 'how': 2, 'are': 1, 'you': 1} 

我搜索了与此问题类似的上一个问题,但我找不到任何有效的方法。一个接近的解决方案似乎是使用正则表达式,但它也不起作用。这可能是因为我实现错误,因为我不熟悉它的实际工作原理。

How to find the count of a word in a string? 这是最后的答案

from collections import * 
import re 
 
Counter(re.findall(r"[\w']+", text.lower())) 

我还尝试创建一个非常糟糕的函数,该函数遍历字符串中连续字母的每一种可能排列(最多 8 个字母左右)。这样做的问题是

1) 它比应该的要长很多

2) 它添加了额外的单词。例如:如果字符串中有“hello”,也会找到“hell”。

我不太熟悉正则表达式,这可能是执行此操作的正确方法。

请您参考如下方法:

d, w = "hello&^uevfehello!`.<hellohow*howdhAreyou", ["hello","how","are","you"] 
import re, collections 
pattern = re.compile("|".join(w), flags = re.IGNORECASE) 
print collections.Counter(pattern.findall(d)) 

输出

Counter({'hello': 3, 'how': 2, 'you': 1, 'Are': 1})