Alexi Reade
Alexi Reade

Reputation: 3

Retrieving a random word from a textfile

Making a hangman game, trying to retrieve a word from a text file

import time
import random

def start():
    f = open(“wordlist.txt”).read()
    for line in f:
        for word in line.split():
            hangman = random.choice(word)

I expected it to retrieve a random word from the text file, but when i implement a print option to check, it print the ENTIRE list, leading me to belive it’s not picking one word.

The print functions I tried were:

print(hangman)

And

print(word)

This is the list in the text file:

Python
Program
rrrrr
mario
luigi
bowser
peach
daisy
wario
waluigi
yoshi

Upvotes: 0

Views: 1014

Answers (1)

Querenker
Querenker

Reputation: 2365

Instead of iterating over each word, you can read all lines with readlines and use choice to pick a random line. So you can avoid some common mistakes. In you example you iterate over each word and you update the variablehangman in every step. I think this is not want you want to do?

import random

with open('wordlist.txt') as f:
    print(random.choice(f.readlines()))

Upvotes: 1

Related Questions