简体   繁体   English

在python中重用函数

[英]Reusing functions in python

I'm trying to create a very simple application that fills out Mad Libs.我正在尝试创建一个非常简单的应用程序来填充 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.我可以很好地使用该函数一次,但是如果我尝试在同一个文件上再次使用它,我会收到与“随机”模块有关的“IndexError:无法从空序列中选择”问题。 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)

file.readlines() reads the lines starting from the current position in the file. file.readlines()从文件中的当前位置开始读取行。 The first time you read the file, it leaves the position at the end of the file.第一次读取文件时,它会保留文件末尾的位置。 So when you try to use it again, there's nothing left to read, and it returns an empty list.因此,当您再次尝试使用它时,没有什么可读取的,并且它返回一个空列表。

You need to seek back to the beginning of the file to be able to read it again.您需要回到文件的开头才能再次阅读。

def randomize(file):
    file.seek(0)
    return random.choice(file.readlines())

But it would be simpler if you just read each file once, rather than reading the file each time you want that type of word.但是,如果您只读取每个文件一次,而不是每次需要该类型的单词时都读取文件,那会更简单。

import random

adjectives = open("data\\adjectives.txt", "r+").readlines()
verbs = open("data\\verbs.txt", "r+").readlines()
nouns = open("data\\nouns.txt", "r+").readlines()
colors = open("data\\colors.txt", "r+").readlines()
sports = open("data\\sportsgames.txt", "r+").readlines()

def randomize(file):
    return random.choice(file)

madlib = "One day I was playing {0}. I got bored so I played {1} instead.".format(randomize(verbs), randomize(verbs))

print(madlib)

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

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