简体   繁体   English

为什么我从随机选择函数中得到IndexError?

[英]Why am I getting an IndexError from a random choice function?

I am trying to run this code from the beginners' python book Think Python to do Markov Analysis on a text file. 我正在尝试从初学者的python书中运行代码,以Think Python在文本文件上进行马尔可夫分析。 When I run the code provided as a solution, I get an IndexError: List index out of range from the random.py module. 当我运行作为解决方案提供的代码时,出现IndexError:List索引超出random.py模块的范围。 What do I need to change? 我需要更改什么?

The code should be the answer to Exercise 8 off of Think Python , but I can't get it to work. 该代码应该是Think Python练习8的答案,但我无法使其正常工作。

Traceback: 追溯:

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

Edit: I am running it on a .txt file. 编辑:我正在.txt文件上运行它。 It's the text of a book downloaded from Project Gutenburg. 这是从古腾堡计划(Project Gutenburg)下载的一本书的文字。

The file you are running the program on doesn't have a Gutenberg header. 您正在运行程序的文件没有Gutenberg标头。 It needs to have a line that starts with: 它需要以下列开头的行:

*END*THE SMALL PRINT!

Only text after that will be read (this occurs in the skip_gutenberg_header function). 仅读取其后的文本(这在skip_gutenberg_header函数中发生)。 As an example, running the code on the file 例如,在文件上运行代码

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.

produces (as one example): 产生(作为一个例子):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM