使用正则表达式在 Python 中进行字数统计
使用正则表达式计算文档中英文单词的正确方法是什么?
我尝试过:
words=re.findall('\w+', open('text.txt').read().lower())
len(words)
但似乎我遗漏了几个单词(与 gedit 中的字数相比)。 我做得对吗?
多谢!
What is the correct way to count English words in a document using regular expression?
I tried with:
words=re.findall('\w+', open('text.txt').read().lower())
len(words)
but it seems I am missing few words (compares to the word count in gedit).
Am I doing it right?
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 \w+ 将无法正确计算包含撇号或连字符的单词,例如“can't”将被计为 2 个单词。它还会计算数字(数字串); “12,345”和“6.7”各算作 2 个单词(“12”和“345”、“6”和“7”)。
Using \w+ won't correctly count words containing apostrophes or hyphens, eg "can't" will be counted as 2 words. It will also count numbers (strings of digits); "12,345" and "6.7" will each count as 2 words ("12" and "345", "6" and "7").
这似乎按预期工作。
你为什么要小写你的话?这和计数有什么关系?
我认为以下内容会更有效:
This seems to work as expected.
Why are you lowercasing your words? What does that have to do with the count?
I'd submit that the following would be more efficient:
一旦您通过
_words_list = Words.split()
获得单词列表或通过正则表达式或其他方法进行所需的处理,您可以使用以下方法轻松获得单词计数:Once you have list of words by
_words_list = words.split()
or required processing through regex or other methods, you can easily get a count of words with the following method: