Home > Software engineering >  How to create a loop printing new words from a variable
How to create a loop printing new words from a variable

Time:02-26

I am writing code which takes a prefix, root word, and suffix from 3 separate files, and puts them together (which is the 'finalword' variable in my code). The code works and generates a word.

What I want do is, generate a lot of words (lets say 1000), without having to run my code over and over again. I've thought about using a while loop:

while finalword != 1:
  print(finalword)

But all this does is print the same finalword, not a new one each time. How do I make this loop print new unique words each time?

This is my code:

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)

CodePudding user response:

You are going to have to make some sort of repeated random choices. Whether you do it in a loop or not is up to you.

As I don't have your files, I made this to provide a minimal reproducible example.

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

Now to get to your problem, without a loop I would use 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)

Alternatively, if you want to be lighter on memory, just put your random.choice and concatenation calls inside a loop:

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
  • Related