【问题标题】:How to print the meaning of word only while using the Oxford API in Python?如何在 Python 中使用 Oxford API 时仅打印单词的含义?
【发布时间】:2019-03-03 05:49:52
【问题描述】:

我通过调用牛津词典 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"
        }
    ]
}

【问题讨论】:

  • 哪个定义?
  • "定义": [“通过向(某人)提供自己的服务或资源,使他们更容易或可能做某事”],
  • print(r.text['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'] [0]) TypeError: 字符串索引必须是整数
  • 使用r.data 而不是r.text
  • 我的回答对你有用吗?

标签: python json api


【解决方案1】:

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

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

【讨论】:

    【解决方案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))
    

    【讨论】:

    • 你能提供一个相同的代码吗?我是这些新手,我不知道该怎么做。告诉我代码会很有帮助
    • 我已经提交了工作代码。您将不得不使用 filter 参数。您可以向 API 团队发送一封电子邮件,询问他们是否无法使其正常工作。 api@oxforddictionaries.com
    • QUERY_FILTER = 'grammaticalFeatures=singular,past;lexicalCategory=noun' 在 queerry_filter 我正在编写定义,但它仍然没有出现并显示错误
    • 我不确定你在说哪个错误。我正在添加一个没有过滤器的版本。代码被包裹在一个函数下,所以调用者只取回定义列表。
    【解决方案3】:

    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")
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 2018-10-19
      • 1970-01-01
      相关资源
      最近更新 更多