Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pulling a random word/string from a line in a text file in python

Tags:

python

I have a text file that has six words on one line, I need to randomly generate a word from that line. The text file name is WordsForGames.txt. I am making a hangman game. This what I have so, far. I am a little lost please help

import random
import os
print(" Welcome to the HangMan game!!\n","You will have six guesses to get the answer correct, or you will loose!!!",)
words = open("../WordsForGames.txt")
like image 732
Michael Schultz Avatar asked Sep 25 '15 01:09

Michael Schultz


2 Answers

It could be as simple as:

import random
print(random.choice(open("WordsForGames.txt").readline().split()))

The words are read from the first line of the file and converted into an array, then a random choice is made from that array.

If the words are instead on separate lines (or spread across lines), use read() instead of readline().

like image 66
paxdiablo Avatar answered Sep 27 '22 22:09

paxdiablo


Your line words = open("../WordsForGames.txt") does not read the file, it just opens it for reading or possibly writing if you add additional flags.

You need to read the line or lines using readlines(), for example, and then most likely split the words into a list and then randomly select one of the words. Something like this:

import random 

# get the first line if this is the one with the words words
lines = open("../WordsForGames.txt").readlines() 
line = lines[0] 

words = line.split() 
myword = random.choice(words)
like image 44
Thane Plummer Avatar answered Sep 27 '22 21:09

Thane Plummer