[Python]用正则表达式进行word Count

来源:互联网 发布:系统工程师 软件开发 编辑:程序博客网 时间:2024/05/20 06:31
# regular  express to Count word
import re
import sys
word_re = re.compile(r'\W')
#line = 'How are you?'
sum = 0
#f = open("test.txt")
f = open(sys.argv[1])
for i in f.readlines():
    word_count = len([word for word in word_re.split(i) if word])
    sum += word_count
#    print word_count
f.close()
print sum


使用:在本目录下,新建一个test,里边写一些,英语句子。

python wordCount.py test


解释:1,正则表达式,这个可以去搜“30分钟学会正则表达式”

2,用读取的行,判断有多少个字符串,也就是word。然后每个行都累加起来。