如何创建一个循环打印变量中的新词

How to create a loop printing new words from a variable

我正在编写代码,它从 3 个单独的文件中获取前缀、词根和后缀,并将它们放在一起(这是我代码中的 'finalword' 变量)。该代码有效并生成一个单词。

我想要做的是生成很多单词(比如 1000 个),而不必一遍又一遍地 运行 我的代码。我考虑过使用 while 循环:

while finalword != 1:
  print(finalword)

但这所做的只是打印相同的 finalword,而不是每次都打印一个新的。如何让这个循环每次都打印新的唯一单词?

这是我的代码:

import random

# finalword components
file = open("prefixes.py", "r")  # opening word list
prefixes = file.read().split("\n")  # splitting all the lines
xprefixes = random.choice(prefixes)  # getting a random word from the file

file = open("words.py", "r")
words = file.read().split("\n")
xwords = random.choice(words)

file = open("suffix.py", "r")
suffix = file.read().split("\n")
xsuffix = random.choice(suffix)

# final word, which combines words from the lists
finalword = (f'{xprefixes}{xwords}{xsuffix}')
print(finalword)

您将不得不做出某种重复的随机选择。是否循环执行取决于您。

因为我没有你的文件,所以我做这个是为了提供一个 minimal reproducible example

prefixes = ['un', 'non', 're']
words = ['read', 'yield', 'sing']
suffixes = ['ing', 'able']

现在解决你的问题,如果没有循环,我会使用 random.choices:

import random

N = 6
# finalword components
xprefixes = random.choices(prefixes, k = N)  # getting a random word from the file
xwords = random.choices(words, k = N)
xsuffixes = random.choices(suffixes, k = N)

# final word, which combines words from the lists
finalwords = [f'{xprefix}{xword}{xsuffix}' for xprefix, xword, xsuffix in zip(xprefixes, xwords, xsuffixes)]

for finalword in finalwords:
    print(finalword)

或者,如果您想减少内存,只需将 random.choice 和串联调用放在一个循环中:

for _ in range(N):
   xprefixes = random.choice(prefixes)  # getting a random word from the file
   xwords = random.choice(words)
   xsuffix = random.choice(suffixes)

   # final word, which combines words from the lists
   finalword = f'{xprefixes}{xwords}{xsuffix}'
   print(finalword)
unreadable
reyielding
rereadable
resinging
rereading
unreadable