【发布时间】:2017-08-27 17:52:29
【问题描述】:
我正在学习 Python,并拼凑了一个随机句子生成器来练习。如何为后续部分保留第一个随机选择的名称?
我有这个:
def random_name():
line_num = 0
selected_line = ''
with open('names.txt') as f:
while 1:
line = f.readline()
if not line: break
line_num += 1
if random.uniform(0, line_num) < 1:
selected_line = line
return selected_line.strip()
重复动词和名词。然后我定义句子:
def MakeSentence(): #makes sentence by combining name, verb, and noun
x = random_name() + " is " + random_verb() + " " + random_noun()
return x
print("Type Yes to continue.")
print("\n")
print("Enter 'Q' to quit.")
print("\n")
response = 'x' #generic response as to not cause problems
while (response != 'Q'): #case switch kills it all
response = input("Would you like to continue?\n")
if response == 'Q':
break
elif response == 'Yes':
print(MakeSentence())
response = input("Is " + random_name() + " correct?\n")
if response == 'Q':
break
elif response == 'Yes':
print(random_name() + " is correct.\n")
【问题讨论】:
-
你需要知道我们很多/大多数人都不愿意通读这么多代码,更不用说调试了。你需要问一些简短的、具体的编程问题,这些问题有明确的答案。您可能应该阅读帮助文件。这并不是说以任何方式阻止您,只是告诉您期望什么。欢迎来到 SO!
-
你一遍又一遍地打电话给
random_name。你不能只调用一次并将结果存储在一个变量中吗? -
谢谢你们。以后我会尽量简洁。谢谢,Carcigenicate,我想你是对的 :)
-
def MakeSentence周围的缩进是否正确? -
提示:不要使用
while 1: ...使用for line in f: ...,这将终止而无需中断。