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

sxpgvts3  于 2022-12-17  发布在  Python
关注(0)|答案(2)|浏览(127)

所以我有一本字典,里面有一堆单词作为键,它们的定义作为值。
例如,单词列表. 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文本文件中字典中的一个随机单词?

b5buobof

b5buobof1#

你需要在你的代码中打开那个文件,用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()将从一个列表中选择一个随机元素,因此你只需要将你的dict作为一个列表传递给它,参数为random.choice(list(your_dict))
编辑:op编辑了他的问题,去掉了word_list. txt样本中每个键的单引号。这段代码只有在键被单引号或双引号括起来的情况下才能工作。

toe95027

toe950272#

首先,你需要修正你的txt文件。这也可能是一个json文件,但是要使它成为一个json文件,你需要修改代码。但是对于将来的json来说,这是正确的方法。你需要删除words =。你还需要把你的键(apple,today,those 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."
}

下面是一些代码。

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

相关问题