繁体   English   中英

从python中的文本文件中的一行中拉出一个随机单词/字符串

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

可以很简单:

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

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

如果单词在不同的行上(或跨行分布 ),请使用read()而不是readline()

您可以使用.readline()函数从文件中读取一行,然后根据您用于行中单词的分隔符将字符串拆分为字符串列表。 然后random.choice()从列表中随机选择一个单词。

另一个建议是使用with语句来处理文件,以便with语句可以自动处理为您关闭文件。

示例 -

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)

如果单词在单独的行上,您可以使用.read()而不是.readline()作为(以上逻辑的其余部分相同) -

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

你的行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)

最短的解决方案

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM