简体   繁体   English

python,指定长度的无限随机句子生成器

[英]python ,infinite random sentence generator of specified length

I have a dictionary 我有一本字典

{
    'went': ['up', 'up'],
    'water': ['spout'],
    'all': ['the'],
    'again': [],
    'up': ['the', 'all', 'the'],
    'spider': ['went', 'out', 'went']
}    

... created from a text file(filename) ...从文本文件(文件名)创建

Based on this dictionary I have to create infinite random sentences of specified length. 基于此字典,我必须创建指定长度的无限随机句子。 It will start with a random word in the dictionary (a key), then pick another random word from the list of words that come after it, then pick another random word from the list of words that come after the second word and so on until it has the required number of words. 它将以字典中的随机词(键)开始,然后从其后的单词列表中选择另一个随机词,然后从第二个单词之后的单词列表中选择另一个随机词,依此类推,直到它具有所需的单词数。 It will then yield all these words as a sentence. 然后,将所有这些单词作为句子产生。

def sentence_generator(filename, length=10):
     """
     Makes up random sentences based on that dictionary.

     Parameters: a filename that refers to a text file to 'imitate',
                 a length that will be the number of words in the generated
                 sentence.  If omitted the length will default to 10.
     """
     random.seed(1) # set the seed for the random generator

     my_dict1 = learn(filename)
     while True:
         for key, value in my_dict1.items(): 
             my_list = my_dict1.values()
             yield my_dict1[key]
             random.choice(sorted(my_list))

I need to know how to use the 'length' in the function. 我需要知道如何在函数中使用“长度”。 I am not sure how 我不确定如何

You are trying to write a generator that yield s length words. 您正在尝试写一个发生器yield小号length的话。 So you could change your the while loop to count the number of words produced and stop after length words. 因此,您可以更改while循环以计算产生的单词数,并在length单词之后停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM