字典中的累积分布

cumulative distribution in dictionary

我正在尝试将累积分布计算到字典中。分布应该从给定的文本中提取字母,并找出它们在文本中出现的时间的概率,并据此计算累积分布。 我不知道我的做法是否正确,但这是我的代码:

with open('text') as infile:
text = infile.read()

letters = list(text)
letter_freqs = Counter(letters(text))
letter_sum = len(letters) 
letter_proba = [letter_freqs[letter]/letter_sum for letter in letters(text)]

现在我不想计算累积分布,也不想像直方图一样绘制它,有人可以帮我吗?

以下至少应 运行(您发布的代码不会):

import collections, itertools

with open('text') as infile:
    letters = list(infile.read())  # not just letters: whitespace & punct, too
    letter_freqs = collections.Counter(letters)
    letter_sum = len(letters)
    letters_set = sorted(set(letters))
    d = {l: letter_freqs[letter]/letter_sum for l in letters_set}
    cum = itertools.accumulate(d[l] for l in letters_set)
    cum_d = dict(zip(letters_set, cum)

现在您在 cum_d 中有了一个映射每个字符的字典,当然不仅仅是字母,因为您没有做任何事情来排除空格和标点符号,映射到该字符及其下方所有字符的累积概率按字母顺序。你打算如何 "plot" 一本字典,不知道。但是,嘿,至少这个 运行,并产生 某些东西 可能至少符合您给出的模糊规格的一种解释任务!-)