python - 字母频率
写一个叫做 hist() 的 Python 函数,这个函数接收一个字符串作为输入,然后通过打印每个字母(大写)出现的次数来展示这些字母的频率。每个字母单独占一行,按照出现次数从多到少排列。
2 个回答
2
一种简单得多的方法是:
import string
def hist(s):
d = {}
for i in s.upper():
if i.isalpha():
d[i] = d[i] + 1 if i in d else 1
for k in sorted(d.keys()):
print k*d[k]
0
你的代码很像,你不需要去读取那个文件。
def hist(inputstr):
lowlet = inputstr.upper()
alphas = 'abcdefghijklmnopqrstuvwxyz'.upper()
occurrences = dict( (letter, 0) for letter in alphas)
total = 0
for letter in lowlet:
if letter in occurrences:
total += 1
occurrences[letter] += 1
letcount = sorted(occurrences.iteritems(),key = lambda x:-x[1])
for letter, count in letcount:
if count>0:
print letter*count