如何从Python文本文件中的字典中打印随机项?



我有一个字典,其中有一堆单词作为键,它们的定义为值。

。, word_list.txt

words = {
happy: "feeling or showing pleasure or contentment.", 
apple: "the round fruit which typically has thin green or red skin and crisp flesh.", 
today: "on or in the course of this present day."
faeces: "waste matter remaining after food has been digested, discharged from the bowels; excrement."
}

如何在Python上打印文本文件中字典中的随机单词?

你需要在你的代码中打开这个文件,用json库加载它,然后你可以做任何随机操作。

要加载文件,必须在元素的末尾适当地添加,。另外,由于您的文件在键之前有一个'words = ',因此需要拆分它。您还需要将单引号替换为双引号:

import json, random
with open('word_list.txt', 'r') as file:
file_text = file.read()
words = json.loads(file_text.split(' = ')[1].replace("'", '"'))
random_word = random.choice(list(words))
print(random_word)

random.choice()将从列表中随机选择一个元素。因此,您只需要将您的字典作为一个列表作为参数传递给它。random.choice(列表(your_dict))

编辑:op编辑了他的问题,删除了word_list.txt样本中每个键的单引号。这段代码只在键是单引号或双引号的情况下才有效。

首先,您需要修复您的txt文件。这也可以是json文件,但要使其成为json文件,您需要修改代码。但对于未来,json是正确的方式。您需要删除单词=。你还需要把你的钥匙(苹果,今天,那些词)放在引号里。下面是固定文件:

{
"happy": "feeling or showing pleasure or contentment.", 
"apple": "the round fruit which typically has thin green or red skin and crisp flesh.", 
"today": "on or in the course of this present day.",
"faeces": "waste matter remaining after food has been digested, discharged from the bowels; excrement."
}

下面是一些代码。

#Nessasary imports.
import json, random
#Open the txt file.
words_file = open("words.txt", "r")
#Turn the data from the file into a string.
words_string = words_file.read()
#Covert the string into json so we can use the data easily.
words_json = json.loads(words_string)
#This gets the values of each item in the json dictionary. It removes the "apple" or whatever it is for that entry.
words_json_values = words_json.values()
#Turns it into a list that python can use.
words_list = list(words_json_values)
#Gets a random word from the list.
picked_word = random.choice(words_list)
#prints is so we can see it.
print(picked_word)

如果你想把它们都放在同一行,就在这里。

#Nessasary imports.
import json, random
#The code to do it.
print(random.choice(list(json.loads(open("words.txt", "r").read()).values())))

最新更新