为什么我从随机选择函数中获取IndexError?

时间:2012-08-11 21:51:50

标签: python random markov

我正在尝试从初学者的python书Think Python中运行this代码来对文本文件进行马尔可夫分析。当我运行作为解决方案提供的代码时,我得到一个IndexError:List索引超出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文件上运行它。这是从Gutenburg项目下载的一本书的文本。

1 个答案:

答案 0 :(得分:0)

您运行该程序的文件没有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