我想知道如何使用我的三连诗节目打印句子。 我的程序随机选择要使用的名词列表。
我的节目:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return(randomPick)
verbs = ["walked","ran","rolled","biked","crawled"];
nouns()
例如,我可以"牛走到小镇。但后来它被淹死了。"然后用我的随机发生器替换名词/韵(牛,镇,淹死)和动词(走路)。
我会以某种方式使用random.randint吗?
我基本上需要一个普通的打印语句,就像我使用随机函数在名词/押韵之间随机选择的示例一样。
答案 0 :(得分:1)
像往常一样(对我来说),可能会有更多的Pythonic方法,但为了得到你的工作,我做了三件事:
将您对nouns()函数的调用分配给'chosen_list'变量。这样就可以使用返回的'randomPick'。
内置一个选择步骤,以便从'selected_list'和动词列表中的列表中获取单个单词
添加了一个带格式的最终打印语句,将单词组合成句子
代码:
import random
def nouns():
nounPersons = ["cow","crowd","hound","clown"];
nounPlace = ["town","pound","battleground","playground"];
rhymes = ["crowned","round","gowned","found","drowned"];
nounPersons2 = ["dog","frog","hog"];
nounPlace2 = ["fog","Prague","smog"];
rhymes2 = ["log","eggnog","hotdog"];
nounList1 = [nounPersons,nounPlace,rhymes]
nounList2 = [nounPersons2,nounPlace2,rhymes2]
nounsList = [nounList1, nounList2]
randomPick = random.choice(nounsList)
return randomPick
verbs = ["walked","ran","rolled","biked","crawled"]
# this is change 1.
chosen_list = nouns()
# select single words from lists - this is change 2.
noun_subj = random.choice(chosen_list[0])
noun_obj = random.choice(chosen_list[1])
rhyme_word = random.choice(chosen_list[2])
verb_word = random.choice(verbs)
# insert words in to text line - this is change 3.
print ("The {} {} to the {}. But then it was {}.".format(noun_subj, verb_word, noun_obj, rhyme_word))