python - 计算唯一单词的数量

标签 python unique words

我想计算文本中的唯一单词数,但我想确保后跟特殊字符的单词不会被区别对待,并且评估不区分大小写。

举这个例子

text = "There is one handsome boy. The boy has now grown up. He is no longer a boy now." 
print len(set(w.lower() for w in text.split()))

结果是 16,但我希望它返回 14。问题是那个“男孩”。由于标点符号的原因,“boy”和“boy”的评估方式不同。

最佳答案

import re
print len(re.findall('\w+', text))

使用 regular expression让这变得非常简单。您需要记住的只是确保所有字符都在 lowercase 中。 ,最后使用 set 组合结果以确保没有重复的项目。

print len(set(re.findall('\w+', text.lower())))

关于python - 计算唯一单词的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16048819/

相关文章:

Excel:仅计算来自 Countif 的唯一单元格

django - django独特领域

c - 输出正确的单词

php - 文本语料库中的单词匹配非常慢

python - 如何将 pandas 中的一列字典转换为单独的列?

python - 在 Python 中使用 zlib crc32_combine

python - Altair 中的多线图 - 数据格式?

python - 如何使用 tkinter 自动执行按钮的操作?

Redis唯一增量

mysql - 从数据库中显示的最大字数