我在学习Python,并且拼凑了一个随机的句子生成器来练习。我如何保留随后部分的第一个随机选择的名称?在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
谢谢你们两位。我会尽量在将来更简洁。谢谢,Carcigenicate,我想你是对的:) – afilmforthefuture