vendredi 4 août 2017

How to Print Random Words from a Text File

I have a text file with 2000 words, one word on each line. I'm trying to create a code that prints out two random words from the textfile on the same line every 10 seconds. The beginning part of my text file is shown below:

slip
melt
true
therapeutic
scarce
visitor
wild
tickle
.
.
.

The code that I've written is:

from time import sleep
import random

my_file = open("words.txt", "r")


i = 1
while i > 0:
    number_1 = random.randint(0, 2000)
    number_2 = random.randint(0, 2000)
    word_1 = my_file.readline(number_1)
    word_2 = my_file.readline(number_2)
    print(word_1.rstrip() + " " + word_2.rstrip())
    i += 1
    sleep(10)

When I execute the code instead of printing two random words it starts printing all the words in order from the top of the text. I'm not sure why this is happening since number_1 and number_2 are inside the loop so every time two words print number_1 and number_2 should be changed to two other random numbers. I don't think replacing number_1 and number_2 outside of the loop will work either since they'll be fixed to two values and the code will just keep on printing the same two words. Does anyone know what I can do to fix the code?




Aucun commentaire:

Enregistrer un commentaire