计算文本文件中字母的频率[关闭]

计算文本文件中字母的频率[关闭],第1张

计算文本文件字母的频率[关闭]

用途

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)


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5667794.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存