索引超出范围随机函数增加

时间:2015-12-26 21:38:50

标签: python

我有这个功能,只需打开文本文件和读取行:

def select_word(model):
    lines = model.read().splitlines()
    selectedline = random.choice(lines)
    return [selectedline.split(":")[0],selectedline.split(":")[1]]

当我只为一个人调用这个功能时,没有问题。但是当我不止一次打电话时:

print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)
print select_word(a)

我收到了这个错误:

Traceback (most recent call last):
  File "wordselect.py", line 58, in <module>
    print select_word("noun")   
  File "wordselect.py", line 19, in select_word
    selectedline = random.choice(lines)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 275, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

该功能有什么问题?

3 个答案:

答案 0 :(得分:2)

如果你传递一个空序列,

random.choice会引发IndexError。当您第二次在文件对象上调用.read()时,会发生这种情况(您只能执行一次,后续调用将返回空字符串)。

要修复该功能,您可以读取该文件一次,然后将这些行传递给该函数,例如:

lines = list(model)

def select_word(lines):    
    selectedline = random.choice(lines)
    return selectedline.split(":", 1)

答案 1 :(得分:2)

import random

def select_word(model):
    with open(model, 'r') as f:
        lines = f.read().splitlines()
    selectedline = random.choice(lines)
    return [selectedline.split(":")[0],selectedline.split(":")[1]]

result = select_word('example.txt')
print result

我这样做并没有遇到问题。 只需确保在您打开的文件中有类似的内容。

Line: 1
Line: 2

答案 2 :(得分:0)

文件句柄像生成器一样运行。读完文件后,您已到达流的末尾。

model.seek(0) # bring cursor to start of file after reading, at 2nd line of the function