【发布时间】:2015-06-14 12:51:37
【问题描述】:
我需要创建一个函数,该函数将文本文件作为输入并返回一个大小为 26 的向量,其频率以每个字符的百分比(a 到 z)为单位。这必须不区分大小写。应忽略所有其他字母(例如 å)和符号。
我尝试使用这里的一些答案,尤其是来自“Jacob”的答案。 Determining Letter Frequency Of Cipher Text
这是我目前的代码:
def letterFrequency(filename):
#f: the text file is converted to lowercase
f=filename.lower()
#n: the sum of the letters in the text file
n=float(len(f))
import collections
dic=collections.defaultdict(int)
#the absolute frequencies
for x in f:
dic[x]+=1
#the relative frequencies
from string import ascii_lowercase
for x in ascii_lowercase:
return x,(dic[x]/n)*100
例如,如果我尝试这个:
print(letterFrequency('I have no idea'))
>>> ('a',14.285714)
为什么它不打印字母的所有相对值?还有不在字符串中的字母,例如我的示例中的 z?
以及如何让我的代码打印大小为 26 的向量?
编辑:我尝试过使用 Counter,但它以混合顺序打印 ('a':14.2857) 和字母。我只需要有序序列中字母的相对频率!
【问题讨论】:
标签: python python-3.x