I want to make a random word, but I don't want the output to have the same word, such as a sentence is 'I want GUN GUN', I don't want GUN to repeat, but other words, such as 'I want powerful GUN'. But I don't know how to add the code so that the output has no repeated words.
import random
global word_list
word_list=['bunny','blue','cub','there','is','are','breakfest','the','at','name','eat','end','of','fantastic','dinner','time','go','for','I','you']
def gen_list_of_words(number_of_words, word_list):
listwords=[]
for i in range(number_of_words):
listwords.append(random.choice(word_list))
return listwords
def output_line(listwords,word_line):
line=""
for words in listwords:
if random.random()< 1/((75/100)*len(words)):
line =words.upper() " "
else:
line =words " "
line=line[:-1]
if word_line==0:
line =','
elif word_line==1:
line ="!"
elif word_line==2:
line ="."
return line
def main():
number_of_words=[4,6,4]
listwords=[]
for i in range(3):
listwords.append(gen_list_of_words(number_of_words[i], word_list))
print(output_line(listwords[i],i))
main()
CodePudding user response:
Instead of this,
for i in range(number_of_words):
listwords.append(random.choice(word_list))
you can add this code to your gen_list_of_words
function.
word=random.choice(word_list)
while word in listwords:
word=random.choice(word_list)
listwords.append(word)
It checks if the random word is in the sentence already, and if there's the word, it picks again.
And the final code:
global word_list
word_list=['bunny','blue','cub','there','is','are','breakfest','the','at','name','eat','end','of','fantastic','dinner','time','go','for','I','you']
def gen_list_of_words(number_of_words, word_list):
listwords=[]
for i in range(number_of_words):
word=random.choice(word_list)
while word in listwords:
word=random.choice(word_list)
listwords.append(word)
return listwords
def output_line(listwords,word_line):
line=""
for words in listwords:
if random.random()< 1/((75/100)*len(words)):
line =words.upper() " "
else:
line =words " "
line=line[:-1]
if word_line==0:
line =','
elif word_line==1:
line ="!"
elif word_line==2:
line ="."
return line
def main():
number_of_words=[4,6,4]
listwords=[]
for i in range(3):
listwords.append(gen_list_of_words(number_of_words[i], word_list))
print(output_line(listwords[i],i))
main()
CodePudding user response:
You can try this:
def gen_list_of_words(number_of_words, word_list):
listwords=[]
word_list_t = word_list.copy()
for i in range(number_of_words):
word = random.choice(word_list_t)
word_list_t.remove(word)
listwords.append(word)
return listwords