从python文本文件中的一行中提取随机单词/字符串

Mic*_*ltz 5 python

我有一个文本文件,一行有六个单词,我需要从该行随机生成一个单词。文本文件名为 WordsForGames.txt。我正在制作一个刽子手游戏。到目前为止,这就是我所拥有的。我有点失落请帮助

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")
Run Code Online (Sandbox Code Playgroud)

pax*_*blo 5

可以很简单:

import random
print(random.choice(open("WordsForGames.txt").readline().split()))
Run Code Online (Sandbox Code Playgroud)

从文件的第一行读取单词并转换为数组,然后从该数组中进行随机选择。

如果单词位于单独的行上(或跨行分布),请使用read()代替readline()


Tha*_*mer 2

您的行words = open("../WordsForGames.txt")不会读取该文件,它只是打开它进行读取或可能写入(如果您添加其他标志)。

例如,您需要使用 读取一行或多行readlines(),然后很可能将单词分成一个列表,然后随机选择其中一个单词。像这样的东西:

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)
Run Code Online (Sandbox Code Playgroud)