简体   繁体   中英

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. So you could change your the while loop to count the number of words produced and stop after length words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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