如何仅在Python中使用牛津API时打印单词的含义?

时间:2019-03-03 05:49:52

标签: python json api

我通过调用牛津词典API得到了json文件。我只想查找单词的含义,但是它为我提供了单词的所有信息。实际上,此文件中的含义是DEFINITION。如何使用Python从此json文件中提取DEFINITION部分?

{
    "metadata": {
        "provider": "Oxford University Press"
    },
    "results": [
        {
            "id": "help",
            "language": "en",
            "lexicalEntries": [
                {
                    "entries": [
                        {
                            "etymologies": [
                                "Old English helpan (verb), help (noun), of Germanic origin; related to Dutch helpen and German helfen"
                            ],
                            "grammaticalFeatures": [
                                {
                                    "text": "Transitive",
                                    "type": "Subcategorization"
                                },
                                {
                                    "text": "Present",
                                    "type": "Tense"
                                }
                            ],
                            "homographNumber": "000",
                            "senses": [
                                {
                                    "***definitions***": [
                                        "make it easier or possible for (someone) to do something by offering them one's services or resources"
                                    ],
                                    "examples": [
                                        {
                                            "text": "the teenager helped out in the corner shop"
                                        },
                                        {
                                            "text": "she helped him find a buyer"
                                        },
                                        {
                                            "text": "they helped her with domestic chores"
                                        }
                                    ],
                                    "id": "m_en_gbus0460970.006",
                                    "short_definitions": [
                                        "assist someone to do something"
                                    ],
                                    "subsenses": [
                                        {
                                            "definitions": [
                                                "improve (a situation or problem); be of benefit to"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "legislation to fit all new cars with catalytic converters will help"
                                                },
                                                {
                                                    "text": "upbeat comments about prospects helped confidence"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.012",
                                            "short_definitions": [
                                                "improve situation"
                                            ],
                                            "thesaurusLinks": [
                                                {
                                                    "entry_id": "help",
                                                    "sense_id": "t_en_gb0006913.003"
                                                }
                                            ]
                                        },
                                        {
                                            "definitions": [
                                                "assist (someone) to move"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "I helped her up"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.013",
                                            "notes": [
                                                {
                                                    "text": "with object and adverbial of direction",
                                                    "type": "grammaticalNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "assist someone to move"
                                            ]
                                        },
                                        {
                                            "definitions": [
                                                "assist someone to put on or take off (a garment)"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "she would help him off with his coat"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.014",
                                            "notes": [
                                                {
                                                    "text": "\"help someone on/off with\"",
                                                    "type": "wordFormNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "assist someone with garment"
                                            ]
                                        }
                                    ],
                                    "thesaurusLinks": [
                                        {
                                            "entry_id": "help",
                                            "sense_id": "t_en_gb0006913.001"
                                        }
                                    ]
                                },
                                {
                                    "definitions": [
                                        "serve someone with (food or drink)"
                                    ],
                                    "examples": [
                                        {
                                            "text": "may I help you to some more meat?"
                                        },
                                        {
                                            "text": "she helped herself to a biscuit"
                                        }
                                    ],
                                    "id": "m_en_gbus0460970.017",
                                    "notes": [
                                        {
                                            "text": "\"help someone to\"",
                                            "type": "wordFormNote"
                                        }
                                    ],
                                    "short_definitions": [
                                        "serve someone with food or drink"
                                    ],
                                    "subsenses": [
                                        {
                                            "definitions": [
                                                "take something without permission"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "he helped himself to the wages she had brought home"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.018",
                                            "notes": [
                                                {
                                                    "text": "\"help oneself\"",
                                                    "type": "wordFormNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "take something without permission"
                                            ],
                                            "thesaurusLinks": [
                                                {
                                                    "entry_id": "help_oneself_to",
                                                    "sense_id": "t_en_gb0006913.006"
                                                }
                                            ]
                                        }
                                    ]
                                },
                                {
                                    "definitions": [
                                        "cannot or could not avoid"
                                    ],
                                    "examples": [
                                        {
                                            "text": "he couldn't help laughing"
                                        },
                                        {
                                            "text": "I'm sorry to put you to any inconvenience, but it can't be helped"
                                        }
                                    ],
                                    "id": "m_en_gbus0460970.020",
                                    "notes": [
                                        {
                                            "text": "\"can/could not help\"",
                                            "type": "wordFormNote"
                                        }
                                    ],
                                    "short_definitions": [
                                        "cannot or could not avoid"
                                    ],
                                    "subsenses": [
                                        {
                                            "definitions": [
                                                "cannot or could not stop oneself from doing something"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "she couldn't help herself; she burst into tears"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.021",
                                            "notes": [
                                                {
                                                    "text": "\"can/could not help oneself\"",
                                                    "type": "wordFormNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "cannot or could not stop oneself"
                                            ]
                                        }
                                    ],
                                    "thesaurusLinks": [
                                        {
                                            "entry_id": "cannot_help",
                                            "sense_id": "t_en_gb0006913.005"
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "language": "en",
                    "lexicalCategory": "Verb",
                    "pronunciations": [
                        {
                            "audioFile": "http://audio.oxforddictionaries.com/en/mp3/help_gb_1.mp3",
                            "dialects": [
                                "British English"
                            ],
                            "phoneticNotation": "IPA",
                            "phoneticSpelling": "h?lp"
                        }
                    ],
                    "text": "help"
                },
                {
                    "entries": [
                        {
                            "grammaticalFeatures": [
                                {
                                    "text": "Mass",
                                    "type": "Countability"
                                },
                                {
                                    "text": "Singular",
                                    "type": "Number"
                                }
                            ],
                            "homographNumber": "001",
                            "senses": [
                                {
                                    "definitions": [
                                        "the action of helping someone to do something"
                                    ],
                                    "examples": [
                                        {
                                            "text": "I asked for help from my neighbours"
                                        }
                                    ],
                                    "id": "m_en_gbus0460970.023",
                                    "short_definitions": [
                                        "action of helping"
                                    ],
                                    "subsenses": [
                                        {
                                            "definitions": [
                                                "the fact of being useful"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "the skimpy manual isn't much help for beginners"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.025",
                                            "short_definitions": [
                                                "fact of being useful"
                                            ],
                                            "thesaurusLinks": [
                                                {
                                                    "entry_id": "usefulness",
                                                    "sense_id": "t_en_gb0015781.001"
                                                }
                                            ]
                                        },
                                        {
                                            "definitions": [
                                                "a person or thing that helps"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "he was a great help"
                                                },
                                                {
                                                    "text": "she's been given financial help with travel"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.026",
                                            "short_definitions": [
                                                "person or thing that helps"
                                            ],
                                            "thesaurusLinks": [
                                                {
                                                    "entry_id": "backup",
                                                    "sense_id": "t_en_gb0001080.001"
                                                }
                                            ]
                                        },
                                        {
                                            "definitions": [
                                                "a domestic employee"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "she has taught herself to cook since the defection of the last of the village helps"
                                                },
                                                {
                                                    "text": "the help cleaned up the leftover food and half-drunk cocktails"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.027",
                                            "notes": [
                                                {
                                                    "text": "count noun",
                                                    "type": "grammaticalNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "domestic employee"
                                            ],
                                            "thesaurusLinks": [
                                                {
                                                    "entry_id": "help",
                                                    "sense_id": "t_en_gb0006913.009"
                                                }
                                            ]
                                        },
                                        {
                                            "definitions": [
                                                "giving assistance to a computer user in the form of displayed instructions"
                                            ],
                                            "domains": [
                                                "Computing"
                                            ],
                                            "examples": [
                                                {
                                                    "text": "a help menu"
                                                }
                                            ],
                                            "id": "m_en_gbus0460970.030",
                                            "notes": [
                                                {
                                                    "text": "as modifier",
                                                    "type": "grammaticalNote"
                                                }
                                            ],
                                            "short_definitions": [
                                                "giving assistance to computer user"
                                            ]
                                        }
                                    ],
                                    "thesaurusLinks": [
                                        {
                                            "entry_id": "help",
                                            "sense_id": "t_en_gb0006913.007"
                                        }
                                    ]
                                }
                            ]
                        }
                    ],
                    "language": "en",
                    "lexicalCategory": "Noun",
                    "pronunciations": [
                        {
                            "audioFile": "http://audio.oxforddictionaries.com/en/mp3/help_gb_1.mp3",
                            "dialects": [
                                "British English"
                            ],
                            "phoneticNotation": "IPA",
                            "phoneticSpelling": "h?lp"
                        }
                    ],
                    "text": "help"
                },
                {
                    "entries": [
                        {
                            "homographNumber": "002",
                            "senses": [
                                {
                                    "definitions": [
                                        "used as an appeal for urgent assistance"
                                    ],
                                    "examples": [
                                        {
                                            "text": "Help! I'm drowning!"
                                        }
                                    ],
                                    "id": "m_en_gbus0460970.033",
                                    "short_definitions": [
                                        "appeal for urgent assistance"
                                    ]
                                }
                            ]
                        }
                    ],
                    "language": "en",
                    "lexicalCategory": "Interjection",
                    "pronunciations": [
                        {
                            "audioFile": "http://audio.oxforddictionaries.com/en/mp3/help_gb_1.mp3",
                            "dialects": [
                                "British English"
                            ],
                            "phoneticNotation": "IPA",
                            "phoneticSpelling": "h?lp"
                        }
                    ],
                    "text": "help"
                }
            ],
            "type": "headword",
            "word": "help"
        }
    ]
}

3 个答案:

答案 0 :(得分:2)

无需遍历每个子列表并查找匹配项等,您可以使用以下内容:

text['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['***definitions***'][0]

答案 1 :(得分:2)

使用过滤器API以便仅获取您感兴趣的字段。 参见https://developer.oxforddictionaries.com/documentation#!/Dictionary32entries/get_entries_source_lang_word_id_filters

请参阅下面的代码,以了解如何使用过滤器

import requests
import os
import pprint

app_id = os.getenv('OXFORD_APP_ID', None)
if not app_id:
    raise Exception('Oxford App ID must be provided')

app_key = os.getenv('OXFORD_APP_KEY', None)
if not app_key:
    raise Exception('Oxford App key must be provided')

# This is the part you need to play with
# See https://api-blog.oxforddictionaries.com/2018/02/23/making-sense-of-senses-wordlist-endpoint/ for more info
QUERY_FILTER = 'grammaticalFeatures=singular,past;lexicalCategory=noun'

LANGUAGE = 'en'

WORD_TO_SEARCH = 'dog'

url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/{}/{}/{}'.format(LANGUAGE, WORD_TO_SEARCH, QUERY_FILTER)

r = requests.get(url, headers={'app_id': app_id, 'app_key': app_key})

if r.status_code == 200:
    result = r.json()
    pprint.pprint(result)
else:
    print('There was a problem calling oxford API. Status code is {}'.format(r.status_code))

没有过滤器的版本。

import requests
import os

app_id = os.getenv('OXFORD_APP_ID', None)
if not app_id:
    raise Exception('Oxford App ID must be provided')

app_key = os.getenv('OXFORD_APP_KEY', None)
if not app_key:
    raise Exception('Oxford App key must be provided')


def get_oxford_word_definitions(word, lang='en'):
    r = requests.get('https://od-api.oxforddictionaries.com:443/api/v1/entries/{}/{}'.format(lang, word),
                     headers={'app_id': app_id, 'app_key': app_key})
    if r.status_code == 200:
        return True, r.json()["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["definitions"]
    else:
        return False, 'There was a problem calling oxford API. Status code is {}'.format(r.status_code)


ok, definitions_or_error_msg = get_oxford_word_definitions('dog')
if ok:
    print(definitions_or_error_msg)
else:
    print('Failed to query API. {}'.format(definitions_or_error_msg))

答案 2 :(得分:1)

API结果采用嵌套字典和列表的形式。

如果您不想使用API​​过滤器,则需要import json并以Python对象的形式加载。

y = json.loads(<filename>.text) #filename should be the file where your json is saved
y = y["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0]["definitions"]

for definition in y:
    print (definition)
    print("\n")

上面的代码应打印所有定义。