简体   繁体   中英

Pulling a random word/string from a line in a text file in 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")

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() .

You can read a line from the file using .readline() function and then split the string into a list of strings, based on whatever delimiter you used for the the words in the line . And then random.choice() to randomly select one word from the list.

Another suggestion would be to use with statement for handling the file , so that with statement can handle closing the file automatically for you.

Example -

import random
with open("../WordsForGames.txt") as word_file:
    words = word_file.readline().split() #This splits by whitespace, if you used some other delimiter specify the delimiter here as an argument.
random_word = random.choice(words)

If the words are on separate lines, you can use .read() instead of .readline() as (with rest of the above logic same) -

with open("../WordsForGames.txt") as word_file:
        words = word_file.read().split()

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)

shortest solution

import random
print(random.choice(open('file.txt').read().split()).strip())

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