Reputation: 41
So I have been learning python and I am working on a little project. I have run into a problem though.
What I am trying to do is get the program to pick x amount of words from a text file and then repeating that task x amount of times.
So lets say for example I wanted to have 5 words in the sentence and do this 3 times. The result would be the following:
word1 word2 word3 word4 word5
word1 word2 word3 word4 word5
word1 word2 word3 word4 word5
This is what I have so far:
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
That will generate one word from the list of 1100 words. So then I tried to repeat this task x amount of times but instead it just repeated the same randomly chosen word x amount of times.
Here is that code:
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
So I am running in to two problems really. The first is that it is repeating the same word that was chosen first and second it will do it in each individual line instead of x amount then next line.
Would anyone be able to point me in the right direction to sorting this out?
Upvotes: 3
Views: 243
Reputation: 637
you could abstract it to a function
def my_function(x,y):
#your code here
#you script goes here
my_function(x,y)
you are only generating the random number once, you could need to generate another random number for it to be different (thats where the function could help a lot). Make sure your function definition is before you call it.
Upvotes: 0
Reputation: 7157
Let me explain your code a little bit:
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.
To fix this, you need to random a number each time you want a new word to be outputted.
for x in range(0, 3):
sent = random.randrange(0,1100)
print(Words[sent])
Upvotes: 2
Reputation: 6149
You just need to recompute a new random number each time.
for x in range(0, 3):
sent = random.randrange(0,1100)
print(Words[sent])
Though what might be easier for your case is to use the built in random.choices()
function:
print(random.choices(Words, k=3))
Will print a list of 3 random words from your Words
list.
If you aren't using Python 3.6, then you can just call random.choice(Words)
over and over again.
Upvotes: 0