使用正则表达式在 Python 中进行字数统计

Zhe*_* Li 3 python regex count cpu-word

使用正则表达式计算文档中英文单词的正确方法是什么?

我试过:

words=re.findall('\w+', open('text.txt').read().lower())
len(words)
Run Code Online (Sandbox Code Playgroud)

但似乎我遗漏了几个字(与 gedit 中的字数相比)。我做得对吗?

非常感谢!

MRA*_*RAB 5

使用 \w+ 不会正确计算包含撇号或连字符的单词,例如“不能”将被计为 2 个单词。它还会计算数字(数字串);“12,345”和“6.7”将分别计为 2 个单词(“12”和“345”、“6”和“7”)。