Inconsistent API Results

I am writing a Python Flask dictionary app and I find the API giving back inconsistent results. I am using list comprehensions to extract the data I need, but depending on the word I might get a list index out of range error.

Here is my code:

import json
import requests

app_id='my_app_id'
app_key='my_app_key'

language='en'
word_id='grey' # try changing this word to see what I mean

url='https://od-api.oxforddictionaries.com:443/api/v1/entries/' + language + '/' + word_id.lower()

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

#print("code{}\n".format(r.status_code))
#print("text\n" + r.text)
#print("json\n" + json.dumps(r.json()))

parsed=r.json()

provider=parsed['metadata']['provider']
word=parsed['results'][0]['id']
cat1=parsed['results'][0]['lexicalEntries'][0]['lexicalCategory']
#etms=parsed['results'][0]['lexicalEntries'][0]['entries'][0]['etymologies'][0]
defns1=parsed['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]
defns2=parsed['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][1]['definitions'][0]
example1=parsed['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['examples'][0]['text']
cat2=parsed['results'][0]['lexicalEntries'][1]['lexicalCategory']
defns3=parsed['results'][0]['lexicalEntries'][1]['entries'][0]['senses'][0]['definitions'][0]
example3=parsed['results'][0]['lexicalEntries'][1]['entries'][0]['senses'][0]['examples'][0]['text']

print('Dictionary provider - ' + provider)
print('Word to look up: ' + word)
#print('Etymology of the word - ' + etms)
print(cat1)
print(example1)
print(defns1)
print(defns2)
print(cat2)
print(defns3)
print(example3)

What I need is to get consistent results with every word, or at the very least, a way to extract the word categories, etymology, definitions and example sentences of the different uses.

Comments

  • SimoneSimone Member, Administrator, Moderator admin

    Hi @mmuturi195
    Brilliant, thanks for posting - I'm on it, I've forwarded it internally to the technical team.
    So bear with us, as someone will get back to you with a reply asap!

  • Hi @mmuturi195,

    Thanks for your question. Language data is quite dynamic in that not all words will have the same number of entries, senses, definitions or examples. Results will vary and consequently your parser and output formatting logic needs to be able to cope with the varying options. Fortunately Python makes that kind of logic quite easy. If instead of using direct list indexes (like parsed['results'][0]) you iterate over each list then you can handle varying numbers of items better.

    Here is a quick example of dynamically parsing the JSON result and producing a text output similar to how you have been doing it. This could be extended to produce HTML for a Flask application.

    e.g.

    parsed=r.json()
    
    provider=parsed['metadata']['provider']
    print 'Dictionary provider - ' + provider
    
    for result in parsed['results']:
        word=result['id']
        print u"Word: " + word
        print
    
        for lexical_entry in result['lexicalEntries']:
            print u"Category: " + lexical_entry['lexicalCategory']
    
            for entry in lexical_entry['entries']:
                for etymology in entry.get('etymologies', []):
                    print u"Etymology: " + etymology
    
                for sense_index, sense in enumerate(entry['senses']):
                    print "Sense {}:".format(sense_index)
                    for definition_index, definition in enumerate(sense.get('definitions', [])):
                        print u"Definition {}: '{}'".format(definition_index, definition)
    
                    for example_index, example in enumerate(sense.get('examples', [])):
                        print u"Example {}: '{}'".format(example_index, example['text'])
                    print
            print "End of Entry.\n\n"
    

    This will give output for grey like:
    Dictionary provider - Oxford University Press
    Word: grey

    Category: Verb
    Sense 0:
    Definition 0: '(especially of hair) become grey with age:'
    Example 0: 'he had put on weight and greyed somewhat'
    Example 1: 'a man with greying hair'

    End of Entry.

    Category: Adjective
    Etymology: Old English grǣg, of Germanic origin; related to Dutch grauw and German grau
    Sense 0:
    Definition 0: 'of a colour intermediate between black and white, as of ashes or lead:'
    Example 0: 'grey flannel trousers'
    Example 1: 'his hair was grey and wispy'

    Sense 1:
    Definition 0: 'without interest or character; dull and nondescript:'
    Example 0: 'grey, faceless men'
    Example 1: 'the grey daily routine'

    Sense 2:
    Definition 0: '(of financial or trading activity) not accounted for in official statistics:'
    Example 0: 'the grey economy'

    Sense 3:
    Definition 0: 'relating to an ethnically mixed residential area:'
    Example 0: 'a grey Cape Town suburb'

    End of Entry.

    Category: Noun
    Sense 0:
    Definition 0: 'grey colour or pigment:'
    Example 0: 'dirty intermediate tones of grey'

    Sense 1:
    Definition 0: 'a grey thing or animal, in particular a grey or white horse.'

    End of Entry.

  • Hello, justinfoley. Thank you so much for this! I've been looking into it and I'll share the results of my app once I'm done. Thank you again!

  • SimoneSimone Member, Administrator, Moderator admin

    Hi @mmuturi195!
    Yes, please do share as we are always happy to know how the API is being used, and the results you are getting.
    And if you need any more support, ask away! :)

Sign In or Register to comment.