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

Python中的字母频率

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

Python中的字母频率

您可以使用翻译者配方来删除所有不在中的字符

alpha
。由于这样做使make
letters
中除了字符外仅包含其他字符
alpha
,因此它
n
是正确的分母。

然后,您可以使用a

collections.defaultdict(int)
来计数字母的出现:

import collectionsimport stringdef translator(frm='', to='', delete='', keep=None):    # Python Cookbook Recipe 1.9    # Chris Perkins, Raymond Hettinger    if len(to) == 1: to = to * len(frm)    trans = string.maketrans(frm, to)    if keep is not None:        allchars = string.maketrans('', '')        # delete is expanded to delete everything except        # what is mentioned in set(keep)-set(delete)        delete = allchars.translate(allchars, keep.translate(allchars, delete))    def translate(s):        return s.translate(trans, delete)    return translatealpha = 'abcdefghijklmnopqrstuvwxyz'keep_alpha=translator(keep=alpha)while True:    speech = raw_input("Enter file name:")    wholeFile = open(speech, 'r+').read()    lowlet = wholeFile.lower()    letters = keep_alpha(lowlet)    n = len(letters)    occurrences = collections.defaultdict(int)        for x in letters:        occurrences[x]+=1    for x in occurrences:        print x, occurrences[x], occurrences[x]/float(n)


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

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

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