sarah campolt
sarah campolt

Reputation: 148

Getting a random word from a text file

I am trying to return a word from a text file (so that I can eventually make a game from the word) but right now I get the error

IndexError: string index out of range

this is what my text file looks like

yellow
awesome
barking
happy
dancing
laughing

and this is the code I currently have

import random

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()

Do I have the wrong idea about indexing?

Upvotes: 0

Views: 5278

Answers (3)

Sash Sinha
Sash Sinha

Reputation: 22360

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()

Upvotes: 1

jDo
jDo

Reputation: 4010

When you use readlines(), you get a list of lines. The random module has a handy method for picking a random element from such iterables which eliminates the need for "manually" dealing with indexing: random.choice(iterable).

All you need is this (no for loop necessary):

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

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

    infile.close

main()

To avoid the costly operation of reading the file every time you want a single random word, you could also read the file in main and pass the list to generate_the_word instead:

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()

Upvotes: 0

Leonora Tindall
Leonora Tindall

Reputation: 1521

Your for loop is iterating over every line in the file and indexing into that line. You should also take advantage of Python's context managers, which take care of opening and closing files for you. What you want is to load all the lines:

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

Your second problem is that you aren't properly indexing into those lines with randrange. You want a range between 0 and the max number of lines:

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

You also need to import the random module before this will run.

Your whole program would look like:

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()

You should also note that reading the file every time is inefficient; perhaps read it once and then pick lines from that. You could, for instance, read it in the main function and pass its already-read values to the generate_the_word function.

Upvotes: 0

Related Questions