【问题标题】:Why am I getting an IndexError from a random choice function?为什么我从随机选择函数中得到 IndexError?
【发布时间】:2012-08-11 21:51:50
【问题描述】:

我正在尝试运行 Python 初学者书籍 Think Python 中的 this 代码,以对文本文件进行马尔可夫分析。当我运行作为解决方案提供的代码时,我得到一个 IndexError: List index out of range from the random.py 模块。我需要改变什么?

代码应该是Think Python 中练习 8 的答案,但我无法让它工作。

追溯:

Traceback (most recent call last):
  File "test.py", line 115, in <module>
    main(*sys.argv)
  File "test.py", line 111, in main
    random_text(n)
  File "test.py", line 76, in random_text
    start = random.choice(suffix_map.keys())
  File "/Library/Frameworks/EPD64.framework/Versions/7.3/lib/python2.7/random.py", line 274, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty

编辑:我在 .txt 文件上运行它。这是从古腾堡计划下载的一本书的文本。

【问题讨论】:

  • 你在哪个文本文件上运行它? (它必须以特定格式运行)。
  • 哪个文本文件?你有链接吗? (它必须不符合我在下面的答案中描述的格式)。

标签: python random markov


【解决方案1】:

您正在运行程序的文件没有 Gutenberg 标头。它需要有一行以:

*END*THE SMALL PRINT!

仅读取之后的文本(这发生在skip_gutenberg_header 函数中)。例如,在文件上运行代码

Header info
*END*THE SMALL PRINT!

He was very clever, be it sweetness or be angry, ashamed or only amused, at such a stroke. She had never thought of Hannah till you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself.

产生(作为一个例子):

a stroke. She had never thought of Hannah till you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself. at such a stroke. She had never thought of Hannah till you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself. you were never meant for me?" "I cannot make speeches, Emma:" he soon cut it all himself. cannot make speeches, Emma:" he soon cut it all himself. be it sweetness or be angry, ashamed or only amused, at such a stroke. She had never thought of

【讨论】:

  • 您确定该行与文本中显示的完全一致?尝试注释掉调用skip_gutenberg_header 的行。
  • 我注释掉了对 skip_gutenberg_header 的调用,现在它可以工作了。所以一定是那个功能有问题。
  • 有什么地方可以下载文件吗?
  • 是否有可能您没有从行首粘贴到标题行,或者在运行 Python 文件之前没有保存它?如果头信号文件在那里,它应该可以工作。
  • 另外:那行不是文件中的最后一行,是吗?这只是标题的结尾,对吧?
猜你喜欢
  • 1970-01-01
  • 2020-04-13
  • 2021-01-06
  • 1970-01-01
  • 2019-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 2014-03-27
相关资源
最近更新 更多