Python:如何打印我简单的诗歌

2024-09-30 16:23:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何用我的三连体诗程序打印出句子。 我的程序随机选择要使用的名词列表。在

我的计划:

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()

例如,我可以“牛走到镇上。然后用我的随机化器替换名词/押韵(cow,town,sounded)和动词(walked)。在

我会用吗随机.randint在某种程度上?在

我基本上只需要一个通用的打印语句,就像我用随机数发生器在名词/韵脚之间随机选择的例子一样。在


Tags: 程序random名词cowtownnounsrhymesrhymes2
1条回答
网友
1楼 · 发布于 2024-09-30 16:23:19

像往常一样(对我来说),可能还有一种更像Python的方法,但为了让你的工作发挥作用,我做了三件事:

  1. 将对nomens()函数的调用分配给“choosed\u list”变量。这样就可以使用返回的“randomPick”。

  2. 内置一个选择步骤,从“choosed”列表和动词列表中获取单个单词

  3. 添加了带格式的final print语句以将单词组合成一个句子

代码:

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))

相关问题 更多 >