Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word counts in Python using regular expression

Tags:

python

regex

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 (compared to the word count in gedit). Am I doing it right?

like image 439
Zhe Li Avatar asked Nov 01 '25 17:11

Zhe Li


2 Answers

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").

like image 145
MRAB Avatar answered Nov 04 '25 08:11

MRAB


This seems to work as expected.

>>> import re
>>> words=re.findall('\w+', open('/usr/share/dict/words').read().lower())
>>> len(words)
234936
>>> 
bash-3.2$ wc /usr/share/dict/words
  234936  234936 2486813 /usr/share/dict/words

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=re.findall(r'\w+', open('/usr/share/dict/words').read())
like image 37
Johnsyweb Avatar answered Nov 04 '25 06:11

Johnsyweb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!