Posted Updated Pythona few seconds read (About 94 words)
统计一个文件中某个单词的出现次数
首先有一个最简单的方法,就是用正则匹配
1 2 3
import re tmp = open("123.txt", "r").read() printlen(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)