I'm trying to create a very simple application that fills out Mad Libs. To do this I've opened several files that contain my nouns, adjectives, etc.. and created a function that randomly selects a word in the file given. I can use the function fine once, but if I try to use it again on the same file I get a "IndexError: Cannot choose from an empty sequence" problem having to do with the 'random' module. How can I avoid this and the function that I've created. Here is my code:
import random
adjectives = open("data\\adjectives.txt", "r+")
verbs = open("data\\verbs.txt", "r+")
nouns = open("data\\nouns.txt", "r+")
colors = open("data\\colors.txt", "r+")
sports = open("data\\sportsgames.txt", "r+")
def randomize(file):
return random.choice(file.readlines())
madlib = "One day I was playing {0}. I got bored so I played {1}
instead.".format(randomize(verbs), randomize(verbs))
print(madlib)
Aucun commentaire:
Enregistrer un commentaire