栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

用途

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/661678.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号