import random

lst_who = ['horse', 'lamb', 'deer']
lst_what = ['watch a movie', 'listen to a story', 'have dinner']
lst_where = ['on the grass', 'in the cinema', 'at home']

seed_input = input().strip()
seed = [int(x) for x in seed_input[1:-1].split(',')]

random.seed(seed)

sentence = lst_who[random.randint(0, 2)] + ' ' + lst_what[random.randint(0, 2)] + ' ' + lst_where[random.randint(0, 2)]

print(sentence)

这段代码演示了如何使用 Python 创建一个简单的随机句子生成器。它首先定义了三个列表,分别包含不同的主题 (who)、动作 (what) 和地点 (where)。

然后,代码接收一行用户输入,其中包含一个种子列表。 该种子用于使用 random.seed() 函数初始化随机数生成器。 这确保了对于相同的种子,每次都会生成相同的随机数序列,从而使输出可重现。

接下来,代码使用 random.randint(0, 2) 从每个列表中随机选择一个元素。 最后,它将这些元素组合成一个句子并将其打印出来。

这个例子展示了如何使用随机数生成和种子来创建简单的文本生成器。 通过扩展列表和添加更多语法规则,您可以创建更复杂和有趣的句子生成器。

Python 随机句子生成器:使用随机数和种子生成句子

原文地址: https://www.cveoy.top/t/topic/crcW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录