【问题标题】:cumulative distribution in dictionary字典中的累积分布
【发布时间】:2015-03-14 11:15:31
【问题描述】:

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

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)]

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

【问题讨论】:

  • 查看ScipyHere 是 API 参考的链接。
  • @NoobSaibot 这是什么?
  • letters(text) 的使用已被破坏(letterslist不可 可调用,但您正在尝试调用它)。并且,您要累积 什么 序列? letters 本身? sorted(set(letters))? itertools.accumulate 当然可以进行累积——但作为一个序列,“绘制字典”无论如何看起来很奇怪,因为字典没有顺序......
  • 在我的情况下最好做什么@AlexMartelli。你能给我一个代码的例子吗?
  • @py.codan,当然,看看我的回答。如果您编辑 Q 以精确指定问题,则答案可能会相应更改。至于绘图,请参阅例如stackoverflow.com/questions/12303501/… - 但它不会“绘制字典”(?!),它当然会绘制一个呈现为 sequence 的直方图(字典没有顺序,那么你将如何绘制它?!)

标签: python dictionary histogram cumulative-sum cumulative-frequency


【解决方案1】:

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

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 中有一个字典映射每个字符,当然不仅仅是字母,因为您没有做任何事情来排除空格和标点符号,以及按字母顺序排列的该字符及其下方的所有字符的累积概率。你打算如何“绘制”一本字典,不知道。但是,嘿,至少这确实运行,并产生某些东西,可能符合您为任务给出的模糊规范的至少一种解释!-)

【讨论】:

  • 谢谢@Alex 我要试试这个。我不知道我打算如何绘制字典...我是 python 新手,所以我做了一些失败。
  • @py.codan 你应该看看 matplotlib。它是一个用于绘图的 python 库。它可以生成直方图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2013-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
相关资源
最近更新 更多