我试图实现的是使用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
。如果您或任何人知道如何修复此错误,请留下回复以帮助解决。提前感谢:)
dic
返回的是dict对象,而不是列表,因此不能使用索引来获取第一项。
你可以这样做代替
word = dic.meaning('book')
print(list(word.values())[0])
请注意,在Python和大多数其他语言中,计数从0开始。因此,列表中的第一项是索引0,而不是1。
如果你的想法是获得一个随机项目,你可以使用这个代码
from PyDictionary import PyDictionary
import random
dic=PyDictionary()
word = dic.meaning('book')
random = random.choice(list(word.items()))
print(random)
word
是一个字典,因此您不能用索引访问它的值,您必须使用键来调用它的值。这里,您有一个Noun
键,它的值是一个含义列表。因此,要访问此列表的值,您可以使用:
word = dic.meaning('book')
for i in len(word['Noun']):
print(word['Noun'][i])