#python #json #api
#python #json #API
Вопрос:
Я получил файл json, вызвав Oxford dictionary API. Я хочу найти значение только слова, но это дает мне всю информацию о слове. Значение на самом деле является ОПРЕДЕЛЕНИЕМ в этом файле. Как я могу извлечь часть ОПРЕДЕЛЕНИЯ из этого файла json с помощью Python?
{
"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"
}
]
}
Комментарии:
1. Какое определение?
2. » определения «: [ «упростите или сделайте возможным для (кого-то) что-то сделать, предложив им свои услуги или ресурсы» ],
3. print(r.text[‘results’][0][‘lexicalEntries’][0][‘entries’][0][‘senses’][0][‘definitions’][0]) Ошибка типа: строковые индексы должны быть целыми числами
4. использовать
r.data
неr.text
5. Сработал ли мой ответ для вас?
Ответ №1:
Не вдаваясь в перебор каждого подсписка и поиск совпадений и тому подобное, вы можете просто использовать следующее:
text['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['***definitions***'][0]
Ответ №2:
Используйте filter 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))
Комментарии:
1. можете ли вы предоставить код для того же. Я новичок в этом и не знаю, как сделать то же самое. будет очень полезно, если вы подскажете мне код
2. Я отправил рабочий код. Вам придется поиграть с аргументом filter. Вы можете отправить электронное письмо команде API и спросить их, не можете ли вы заставить его работать. api@oxforddictionaries.com
3. QUERY_FILTER = ‘grammaticalFeatures= единственное число, прошедшее;lexicalCategory = существительное’ здесь, в querry_filter, я пишу определения, но все еще он не запускается и показывает ошибку
4. Я не уверен, о какой ошибке вы говорите. Я добавляю версию без фильтра. Код заключен в функцию, поэтому вызывающий объект просто возвращает список определений.
Ответ №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")
Приведенный выше код должен напечатать все определения.