【问题标题】:python ,infinite random sentence generator of specified lengthpython ,指定长度的无限随机句子生成器
【发布时间】:2016-02-16 06:46:26
【问题描述】:

我有一本字典

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

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

【问题讨论】:

  • 我知道您在这里要做什么,但我没有看到 'the''out' 作为字典中的键。如果这是我们从列表中选择的词,会发生什么?
  • 这是全部功能吗?它输出句子的部分在哪里?
  • 这是我尝试的功能。我在提示符处的输出 ..Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)] on win32 >>> from language import sentence_generator >> > baby = sentence_generator('spider.txt', 5) >>> next(baby) ['the', 'itsy', 'down', 'out', 'and'] >>> next(baby) [' come', 'the'] >>> next(baby) ['spout']
  • lenght 是什么意思?
  • def sentence_generator(filename, length=10):长度为参数,输出的随机句子应具有指定的单词长度,例如:baby = sentence_generator('spider.txt', 5) where长度为 5

标签: python generator


【解决方案1】:

您正在尝试编写一个包含yields length 字词的生成器。因此,您可以更改 while 循环以计算产生的单词数并在 length 单词之后停止。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    • 2020-03-11
    • 2012-05-16
    • 2012-11-23
    相关资源
    最近更新 更多