随机产生句子
nouns = [‘apple‘, ‘ball‘, ‘cat‘, ‘dog‘, ‘elephant‘, ‘fish‘, ‘goat‘, ‘house‘, ‘iceberg‘, ‘jackal‘, ‘king‘, ‘llama‘, ‘monkey‘, ‘nurse‘, ‘octopus‘, ‘pie‘, ‘queen‘, ‘robot‘, ‘snake‘, ‘tofu‘, ‘unicorn‘, ‘vampire‘, ‘wumpus‘, ‘x-ray‘, ‘yak‘, ‘zebra‘] verbs = [‘ate‘, ‘bit‘, ‘caught‘, ‘dropped‘, ‘explained‘, ‘fed‘, ‘grabbed‘, ‘hacked‘, ‘inked‘, ‘jumped‘, ‘knitted‘, ‘loved‘, ‘made‘, ‘nosed‘, ‘oiled‘, ‘puffed‘, ‘quit‘, ‘rushed‘, ‘stung‘, ‘trapped‘, ‘uplifted‘, ‘valued‘, ‘wanted‘] templates = [ ‘Waiter! I found a {{noun}} in my {{noun}}!‘, ‘The {{noun}} {{verb}} the {{noun}}.‘, ‘If you {{verb}} the {{noun}}, ‘ ‘the {{noun}} will get you.‘, "Let‘s go: the {{noun}} is {{verb}}.", ‘Colorless green {{noun}}s {{verb}} furiously.‘ ] import random import words def silly_string(nouns, verbs, templates): # Choose a random template. template = random.choice(templates) # We‘ll append strings into this list for output. output = [] # Keep track of where in the template string we are. index = 0 # Add a while loop here. # After the loop has finished, join the output and return it. if __name__ == ‘__main__‘: print(silly_string(words.nouns, words.verbs, words.templates)) import random import words def silly_string(nouns, verbs, templates): # Choose a random template. template = random.choice(templates) # We‘ll append strings into this list for output. output = [] # Keep track of where in the template string we are. pos = 0 while pos < len(template): if template[pos:pos+8] == ‘{{noun}}‘: # Add a random noun to the output. output.append(random.choice(nouns)) pos += 8 elif template[pos:pos+8] == ‘{{verb}}‘: # Add a random verb to the output. output.append(random.choice(verbs)) pos += 8 else: # Copy a character to the output. output.append(template[pos]) pos += 1 # Join the output into a single string. output = ‘‘.join(output) return output if __name__ == ‘__main__‘: print(silly_string(words.nouns, words.verbs, words.templates))
原文地址:https://www.cnblogs.com/candyYang/p/11674728.html
时间: 2024-10-11 13:58:31