编写一个名为hist()的Python函数,它接受一个字符串作为参数,并通过以字母大小打印每个字母在字符串中出现的次数创建其字母字母频率的直观表示,每个字母在一个单独的行上,从最多到最少分组。
答案 0 :(得分: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]
答案 1 :(得分: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