2016-11-28 81 views
0

我想返回从一个文本文件中的单词(这样我就可以最终使从字游戏),但现在我得到的错误获取从文本随机的Word文件

IndexError: string index out of range 

这是我的文本文件看起来像

yellow 
awesome 
barking 
happy 
dancing 
laughing 

,这是代码我现在有

进口随机

def generate_the_word(infile): 

    for line in infile.readlines(): 
     random_line = random.randrange(line[0], line[len(line) + 1]) 

     print(random_line) 



def main(): 
    infile = open("words.txt","r") 
    generate_the_word(infile) 

    infile.close 


main() 

我对索引有错误的想法吗?

回答

0

您的for循环遍历文件中的每一行并将其索引到该行中。您还应该利用Python的context managers,它负责为您打开和关闭文件。你需要的是加载所有行:

with open(infile) as f: 
    contents_of_file = f.read() 

你的第二个问题是,你没有正确索引与randrange这些行。你想和0之间的范围内的最大行数:

lines = contents_of_file.splitlines() 
line_number = random.randrange(0, len(lines)) 
return lines[line_number] 

您还需要导入random模块之前,这将运行。

你的整个程序看起来像:

import random 

def generate_the_word(infile): 
    with open(infile) as f: 
     contents_of_file = f.read() 
    lines = contents_of_file.splitlines() 
    line_number = random.randrange(0, len(lines)) 
    return lines[line_number] 


def main(): 

    print(generate_the_word("Filename.txt")) 


main() 

你还应该注意的是读取文件每次都是低效的;也许阅读一次,然后从中选择线。例如,您可以在主函数中读取它,并将其已读值传递给generate_the_word函数。

+0

谢谢你这个完美! –

0

当您使用readlines()时,会得到list行。 random模块提供了一种方便的方法,用于从这些迭代中挑选随机元素,从而无需“手动”处理索引:random.choice(iterable)

所有你需要的是这样的(没有for必要环路):

def generate_the_word(infile): 
    return random.choice(infile.readlines()) 

def main(): 
    infile = open("words.txt","r") 
    generate_the_word(infile) 

    infile.close 

main() 

为避免你想一个随机字每一次读取文件的代价高昂的操作,你还可以读取文件中main和列表传递给generate_the_word代替:

import random 

def generate_the_word(word_list): 
    return random.choice(word_list) 

def main(): 
    infile = open("words.txt","r") 
    lines = infile.readlines() 
    infile.close() 
    print generate_the_word(lines) 

main() 
+0

'infile.close'没有被调用,只是抬头。另外,我强烈建议使用上下文管理器,而不是手动打开和关闭文件。你也会在每行之后用'\ n'结尾。 –

+0

@SilverWingedSeraph啊,好赶上:)我刚刚复制了OP的代码,并做了一些编辑。我自己很少使用明确的'open'和'close',但不想过多地更改原始代码,所以在这种情况下我避免了上下文管理和换行。 – jDo

1
import random 

def generate_the_word(infile): 
    random_line = random.choice(open(infile).read().split('\n')) 
    return random_line 

def main(): 
    infile = "words.txt" 
    print(generate_the_word(infile)) 

main()