该函数打印文件中字母的个别频率,但无法忽略非字母,我只想在计算每个字母的百分比频率时计算字母。这是我到目前为止有:Python:如何忽略字符串中的非字母?
from string import ascii_lowercase as lowercase
def calcFrequencies(file):
"""Enter file name in quotations. Shows the frequency of letters in a file"""
infile = open(file)
text = infile.read()
text = text.lower()
text_length = len(text)
counts = [0]*26
for i in range(26):
char=lowercase[i]
counts[i] = 100*text.count(char)/text_length
print("{:.1f}% of the characters are '{}'".format(counts[i],char))
infile.close()
Downvoter,我该如何改进答案? – jayelm
不知道为什么你得到了一个投票,但它适用于我 – Foflo
@Foflo只是建议,如果你关心速度,我相信mhlester的解决方案更快。 – jayelm