簡體   English   中英

如何從 Python 文本文件中的字典中打印隨機項目?

[英]How to print a random item from a dictionary that is in a text file on 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() 將從列表中隨機選擇一個元素。 因此,您只需要將您的字典作為列表傳遞給它作為參數。 隨機選擇(列表(你的字典))

編輯: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())))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM