我想要實作的是使用 PyDictionary 選擇一個單詞的一個隨機含義的能力,使用以下代碼:
word = dic.meaning('book')
print(word)
到目前為止,這只輸出了一長串含義,而不是一個。
{'Noun': ['a written work or composition that has been published (printed on pages bound together', 'physical objects consisting of a number of pages bound together', 'a compilation of the known facts regarding something or someone', 'a written version of a play or other dramatic composition; used in preparing for a performance', 'a record in which commercial accounts are recorded', 'a collection of playing cards satisfying the rules of a card game', 'a collection of rules or prescribed standards on the basis of which decisions are made', 'the sacred writings of Islam revealed by God to the prophet Muhammad during his life at Mecca and Medina', 'the sacred writings of the Christian religions', 'a major division of a long written composition', 'a number of sheets (ticket or stamps etc.'], 'Verb': ['engage for a performance', 'arrange for and reserve (something for someone else', 'record a charge in a police register', 'register in a hotel booker']}
我試圖給我的第一個含義是:
word = dic.meaning('book')
print(word[1])
但是這樣做會導致此錯誤:KeyError: 1
。如果您或任何人知道如何修復此錯誤,請留下回復以提供幫助。提前致謝 :)
uj5u.com熱心網友回復:
dic 正在回傳一個 dict 物件,而不是一個串列 - 所以你不能使用索引來獲取第一項。
你可以這樣做
word = dic.meaning('book')
print(list(word.values())[0])
請注意,在 Python 和大多數其他語言中,計數從 0 開始。因此串列中的第一項是索引 0 而不是 1。
uj5u.com熱心網友回復:
如果您的想法是獲得隨機物品,則可以使用此代碼
from PyDictionary import PyDictionary
import random
dic=PyDictionary()
word = dic.meaning('book')
random = random.choice(list(word.items()))
print(random)
uj5u.com熱心網友回復:
word是一個字典,所以你不能用索引訪問它的值,你必須使用鍵來呼叫它的值。在這里,您有一個Noun鍵,它的值是一個含義串列。因此,要訪問此串列的值,您可以使用:
word = dic.meaning('book')
for i in len(word['Noun']):
print(word['Noun'][i])
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/322297.html
