Python:如何打印我的简单诗

时间:2016-01-05 22:04:45

标签: python python-3.x random

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

我的节目:

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吗?

我基本上需要一个普通的打印语句,就像我使用随机函数在名词/押韵之间随机选择的示例一样。

1 个答案:

答案 0 :(得分:1)

像往常一样(对我来说),可能会有更多的Pythonic方法,但为了得到你的工作,我做了三件事:

  1. 将您对nouns()函数的调用分配给'chosen_list'变量。这样就可以使用返回的'randomPick'。

  2. 内置一个选择步骤,以便从'selected_list'和动词列表中的列表中获取单个单词

  3. 添加了一个带格式的最终​​打印语句,将单词组合成句子

  4. 代码:

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