![计算文本文件中字母的频率[关闭],第1张 计算文本文件中字母的频率[关闭],第1张](/aiimages/%E8%AE%A1%E7%AE%97%E6%96%87%E6%9C%AC%E6%96%87%E4%BB%B6%E4%B8%AD%E5%AD%97%E6%AF%8D%E7%9A%84%E9%A2%91%E7%8E%87%5B%E5%85%B3%E9%97%AD%5D.png)
用途
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)欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)