繁体   English   中英

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

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

我有一本字典

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

...从文本文件(文件名)创建

基于此字典,我必须创建指定长度的无限随机句子。 它将以字典中的随机词(键)开始,然后从其后的单词列表中选择另一个随机词,然后从第二个单词之后的单词列表中选择另一个随机词,依此类推,直到它具有所需的单词数。 然后,将所有这些单词作为句子产生。

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

我需要知道如何在函数中使用“长度”。 我不确定如何

您正在尝试写一个发生器yield小号length的话。 因此,您可以更改while循环以计算产生的单词数,并在length单词之后停止。

暂无
暂无

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

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