用途
collections.Counter():
from collections import Counterwith open(file) as f: c = Counter() for line in f: c += Counter(line)
如果文件不是很大,则可以将所有文件作为字符串读取到内存中,并通过
Counter一行代码将其转换为对象:
c = Counter(f.read())
例:
>>> c = Counter()>>> c += Counter('aaabbbcccddd eee fff ggg')>>> cCounter({'a': 3, ' ': 3, 'c': 3, 'b': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})>>> c += Counter('aaabbbccc')Counter({'a': 6, 'c': 6, 'b': 6, ' ': 3, 'e': 3, 'd': 3, 'g': 3, 'f': 3})或使用
count()字符串方法:
from string import ascii_lowercase # ascii_lowercase =='abcdefghijklmnopqrstuvwxyz'with open(file) as f: text = f.read().strip() dic = {} for x in ascii_lowercase: dic[x] = text.count(x)

![计算文本文件中字母的频率[关闭] 计算文本文件中字母的频率[关闭]](http://www.mshxw.com/aiimages/31/661678.png)
