0

我正在尝试从初学者的 Python 书籍 Think Python 中运行此代码,以对文本文件进行马尔可夫分析。当我运行作为解决方案提供的代码时,我得到一个 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 文件上运行它。这是从古腾堡计划下载的一本书的文本。

4

1 回答 1

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
于 2012-08-11T22:08:35.577 回答