简体   繁体   English

如何使用 PyDictionary 获取单词的一个含义?

[英]How to get one meaning of a word with PyDictionary?

What I am trying to achieve is the ability to choose one random meaning of a word with PyDictionary, using this code:我想要实现的是使用 PyDictionary 选择一个单词的一个随机含义的能力,使用以下代码:

word = dic.meaning('book')
print(word)

So far, this only outputs a long list of meanings, instead of just one.到目前为止,这只输出了一长串含义,而不是一个。

{'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']}

What I have tried to do to give me the first meaning is:我试图给我的第一个含义是:

word = dic.meaning('book')
print(word[1])

But doing this, results in this error: KeyError: 1 .但是这样做会导致此错误: KeyError: 1 If you or anyone knows how to fix this error, please help out by leaving a reply.如果您或任何人知道如何修复此错误,请留下回复以提供帮助。 Thanks in advance :)提前致谢 :)

dic is returning a dict object, not a list - so you can't use indexes to get the first item. dic返回一个 dict 对象,而不是一个列表 - 所以你不能使用索引来获取第一项。

You can do this instead你可以这样做

word = dic.meaning('book')
print(list(word.values())[0])

Note that in Python and most other languages, counting starts with 0. So the first item in a list is index 0 not 1.请注意,在 Python 和大多数其他语言中,计数从 0 开始。因此列表中的第一项是索引 0 而不是 1。

If your idea is to get a random item, you can use this code如果您的想法是获得随机物品,则可以使用此代码

from PyDictionary import PyDictionary
import random

dic=PyDictionary()
word = dic.meaning('book')
random = random.choice(list(word.items()))
print(random)

word is a dictionary, so you cannot access its values with indexes, you have to use keys to call its values. word 是一个字典,所以你不能用索引访问它的值,你必须使用键来调用它的值。 Here, you have a 'Noun' key, wich its values is a list of meanings.在这里,您有一个“名词”键,它的值是一个含义列表。 So inorder to access the values of this list, you can:因此,为了访问此列表的值,您可以:

word = dic.meaning('book')
for i in len(word['Noun']):
    print(word['Noun'][i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM