[英]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. 文本文件名是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()
. 如果单词在不同的行上(或跨行分布 ),请使用read()
而不是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 . 您可以使用.readline()
函数从文件中读取一行,然后根据您用于行中单词的分隔符将字符串拆分为字符串列表。 And then random.choice()
to randomly select one word from the list. 然后random.choice()
从列表中随机选择一个单词。
Another suggestion would be to use with
statement for handling the file , so that with
statement can handle closing the file automatically for you. 另一个建议是使用with
语句来处理文件,以便with
语句可以自动处理为您关闭文件。
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) - 如果单词在单独的行上,您可以使用.read()
而不是.readline()
作为(以上逻辑的其余部分相同) -
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. 你的行words = open("../WordsForGames.txt")
不读取文件,它只是打开它进行读取或者如果添加其他标志可能会写入。
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. 例如,您需要使用readlines()
读取一行或多行,然后很可能将单词拆分为一个列表,然后随机选择其中一个单词。 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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.