简体   繁体   中英

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?

readline() doesn't take any parameters and just returns the next line in your file input*. Instead, try to create a list using readlines() , then choose randomly from that list. So here, you'd make word_list = my_file.readlines() , then choose random elements from word_list .

*Correction: readline() does take a parameter of the number of bytes to read. The documentation for the function doesn't seem to explicitly state this. Thanks E. Ducateme!

my_file.readline(number_1) does not do what you want. The argument for readline is the max size in bytes of a line you can read rather than the position of the line in the file.

As the other answer mentioned, a better approach is to first read the lines into a list and then randomly select words from it:

from time import sleep
import random

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM