我正在编写代码,从3个单独的文件中提取前缀、根单词和后缀,并将它们放在一起(这是代码中的"finalword"变量).代码工作并生成一个单词.

我想做的是,生成大量单词(比如1000个),而不必反复运行代码.我考虑过使用while循环:

while finalword != 1:
  print(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)

推荐答案

你将不得不做一些重复的随机 Select .你是否在一个循环中做这件事取决于你自己.

因为我没有你的文件,我做这个是为了提供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

Python相关问答推荐

云上Gunicorn的Flask-socketIO无法工作

如何使用函数正确索引收件箱?

有什么方法可以避免使用许多if陈述

Python Hashicorp Vault库hvac创建新的秘密版本,但从先前版本中删除了密钥

Select 用a和i标签包裹的复选框?

如何比较numPy数组中的两个图像以获取它们不同的像素

韦尔福德方差与Numpy方差不同

运行总计基于多列pandas的分组和总和

如何在Windows上用Python提取名称中带有逗号的文件?

可变参数数量的重载类型(args或kwargs)

将输入管道传输到正在运行的Python脚本中

如何从pandas的rame类继承并使用filepath实例化

Pandas DataFrame中行之间的差异

Odoo 16使用NTFS使字段只读

给定高度约束的旋转角解析求解

如何在turtle中不使用write()来绘制填充字母(例如OEG)

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

判断solve_ivp中的事件

在单次扫描中创建列表

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?