2 回答
TA贡献1757条经验 获得超8个赞
尝试这个
# get the total number, excluding spaces
total = sum([val for key,val in sorted_letter_frequency[:8] if key != ' '])
for key, value in sorted_letter_frequency[:8]:
# ignore space again
if key == ' ': continue
# print out frequency as percentage of the total
print('{} : {}%'.format(key, float(value) / total * 100)
TA贡献1804条经验 获得超3个赞
如果您只想计算字母,则需要在构建字典时进行检查
import string
valid = string.ascii_letters + string.digits
for letter in words:
if letter in valid:
if letter in letter_frequency_dict:
letter_frequency_dict[letter] += 1
else:
letter_frequency_dict[letter] = 1
至于百分比,您需要获取总字母数并使用它来计算百分比
total = sum(letter_frequency_dict.values())
for key, value in sorted_letter_frequency[:8]:
print('{} : {}%'.format(key, (float(value) / float(total) * 100.0))
添加回答
举报