统计一个文件中某个单词的出现次数

首先有一个最简单的方法,就是用正则匹配

1
2
3
import re
tmp = open("123.txt", "r").read()
print len(re.findall("hello", tmp))

还可以利用Counter来实现更多的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import collections
import re

pa = re.compile("\w+")
counter = collections.Counter(patt.findall(open('reparser.py','rt').read()))

# top 100
for word, times in counter.most_common(100):
print word, times

# find word
counter_dict = dict(counter.most_common(0))
tobefind = 'hello'
print tobefind, counter_dict.get(tobefind, 0)

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×