如何访问python列表中的深层值?

2024-06-26 16:36:59 发布

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

我正在尝试使用以下代码获取某些单词的定义:

import requests

url = requests.get("https://api.dictionaryapi.dev/api/v2/entries/en_US/fish")

a = url.text()

print(a)

上述代码段中的链接返回如下值:

[{"word":"fish","phonetics":[{"text":"/fɪʃ/","audio":"https://lex-audio.useremarkable.com/mp3/fish_us_1.mp3"}],"meanings":[{"partOfSpeech":"noun","definitions":[{"definition":"A limbless cold-blooded vertebrate animal with gills and fins and living wholly in water.","example":"the sea is thick with fish"}]},{"partOfSpeech":"intransitive verb","definitions":[{"definition":"Catch or try to catch fish, typically by using a net or hook and line.","synonyms":["go fishing","angle","cast","trawl"],"example":"he was fishing for bluefish"}]}]},{"word":"fish","phonetics":[{"text":"/fɪʃ/","audio":"https://lex-audio.useremarkable.com/mp3/fish_us_1.mp3"}],"meanings":[{"partOfSpeech":"transitive verb","definitions":[{"definition":"Mend or strengthen (a beam, joint, mast, etc.) with a fish."}]},{"partOfSpeech":"noun","definitions":[{"definition":"A flat plate of metal, wood, or another material that is fixed on a beam or across a joint in order to give additional strength, especially on a ship's damaged mast or spar as a temporary repair."}]}]}]

现在,我想从上面的结果中得到第一个定义。我怎么得到它


Tags: orandtexthttpsapiurl定义with
2条回答

复杂的JSON文档和对此类文档的查询与处理XML文档相比会带来类似的问题;一个可以使用一组自定义的列表理解和实用功能,但是一个应该使用一个专用工具

要在Python中操作JSON文档,您可以查看jsonpath_ng

  • 要提取的项是使用JSONPath表达式定义的,该表达式相当于XML的XPath
  • 只需添加/更新JSONPath表达式即可提取更多/新项

在下一个示例中,QUERIES中定义的JSONPath表达式将在JSON文档上逐个运行:

import requests
import jsonpath_ng
import json


URL = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/fish'
QUERIES = {
    'First kind, first meaning, first definition': jsonpath_ng.parse('[0].meanings[0].definitions[0].definition'),
    'All kind, first definitions': jsonpath_ng.parse('[*].meanings[0].definitions[0].definition'),
    'All definitions': jsonpath_ng.parse('[*].meanings[*].definitions[*].definition')
}


if __name__ == '__main__':
    jsdata = requests.get(URL).json()
    for name, query in QUERIES.items():
        print(f' - {name}  -')
        for match in query.find(jsdata):
            print(json.dumps(match.value, indent=2))
        print()

试试这个

s = [...]
for i in s:
    print(i['word'],[ k['definition'] for j in i['meanings'] for k in j['definitions']])

相关问题 更多 >