JSON导航

2024-10-06 06:49:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将Websters字典实现到这个python代码中,以便可以查找单词的定义

正如Trigonom指出的,我可以在JSON中搜索“shortdef”

@bot.command()
async def define(ctx, *, search):
    with urllib.request.urlopen('https://dictionaryapi.com/api/v3/references/collegiate/json/' + search + '?key=632c5b56-d2ec-4c66-a432-93c5a5994748') as url:
        lk = url.read()
        word_dict = json.loads(lk)
        defin = word_dict[0]['shortdef']
        print (defin)

我在搜索“猎枪”时得到此输出:

['a usually smoothbore shoulder weapon capable of firing shot at short ranges', 'an offensive football formation in which the quarterback plays a few yards behind the line of scrimmage and the other backs are scattered as flankers or slotbacks']

我如何从中得到第一个定义

https://dictionaryapi.com/products/api-collegiate-dictionary

https://dictionaryapi.com/products/json#sec-2.dt


Tags: thehttpscomapijsonurlsearch定义
2条回答
@bot.command()
async def define(ctx, *, search):
    with urllib.request.urlopen('https://dictionaryapi.com/api/v3/references/collegiate/json/' + search + '?key=632c5b56-d2ec-4c66-a432-93c5a5994748') as url:
        lk = url.read()
        word_dict = json.loads(lk)
        defin = word_dict[0]['shortdef'][0]
        print (defin)

如错误所示,JSON结果是一个列表。特别是对象列表

有多个shortdef,您需要解析每个对象

results = [x['shortdef'] for x in json.loads(lk)]

示例输出

[['a small vessel for travel on water',
  'ship',
  'a boat-shaped container, utensil, or device'],
 ['to place in or bring into a boat', 'to go by boat'],
 ['a pole-handled hook with a point or knob on the back used especially to pull or push a boat, raft, or log into place'],
 ['refugees fleeing by boat'],
 ['a low-cut shoe with a slip-resistant sole'],
 ['an express train for transporting passengers between a port and a city'],
 ['a small portable boat used in an amphibious military attack or in land warfare for crossing rivers or lakes'],
 ['a seaplane with a hull designed for floating'],
 ["a ship's boat of medium size used for general-purpose work"],
 ['pt boat']]

相关问题 更多 >