gpt4 book ai didi

python - 从单词列表中创建句子 x 次

转载 作者:行者123 更新时间:2023-11-28 17:10:15 26 4
gpt4 key购买 nike

所以我一直在学习 python,并且正在做一个小项目。不过我遇到了一个问题。

我想做的是让程序从文本文件中选择 x 个单词,然后重复该任务 x 次。

举个例子,我想在句子中包含 5 个单词,然后重复 3 次。结果如下:

word1 word2 word3 word4 word5
word1 word2 word3 word4 word5
word1 word2 word3 word4 word5

这是我目前所拥有的:

import random

word_file = "words.txt" #find word file
Words = open(word_file).read().splitlines() #retrieving and sorting word file

sent = random.randrange(0,1100) #amount of words to choose from in list
print(Words[sent]) #print the words

这将从 1100 个单词的列表中生成一个单词。因此,我尝试重复此任务 x 次,但它只是重复相同的随机选择的单词 x 次。

这是代码:

import random

word_file = "words.txt" #find word file
Words = open(word_file).read().splitlines() #retreiving and sorting word file
sent = random.randrange(0,1100) #amount of words to choose from in list

for x in range(0, 3): #reapeat 3 times
print(Words[sent]) #print the words

所以我真的遇到了两个问题。首先是它重复第一个选择的同一个词,其次它将在每一行中重复,而不是在下一行中重复 x 数量。

谁能给我指出正确的方向来解决这个问题?

最佳答案

让我稍微解释一下您的代码:

sent = random.randrange(0,1100) # <= returns a random number in range 0 => 1100 , this will not be changed.
for x in range(0, 3):
print(Words[sent]) # <= This line will print the word at the position sent, 3 times with the same Words and sent so it will be repeated the same word 3 times.

要解决此问题,您需要在每次要输出新单词时随机生成一个数字。

for x in range(0, 3):
sent = random.randrange(0,1100)
print(Words[sent])

关于python - 从单词列表中创建句子 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48070757/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com