使用正则表达式在Python中计算字数 [英] Word counts in Python using regular expression

查看:127
本文介绍了使用正则表达式在Python中计算字数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用正则表达式对文档中的英语单词进行计数的正确方法是什么?

What is the correct way to count English words in a document using regular expression?

我尝试过:

words=re.findall('\w+', open('text.txt').read().lower())
len(words)

但似乎我缺少几个单词(与gedit中的单词数比较)。
我做对了吗?

but it seems I am missing few words (compares to the word count in gedit). Am I doing it right?

非常感谢!

推荐答案

使用\w +不能正确计算包含撇号或连字符的单词,例如,不能将被计为2个单词。它还将计算数字(数字字符串); b,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").

这篇关于使用正则表达式在Python中计算字数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆