forked from tuanlc/oxford-CLI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict.py.default
93 lines (72 loc) · 3.13 KB
/
dict.py.default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#Develop by tlcong [email protected]
import requests
import json
import sys
# TODO: replace with your own app_id and app_key
app_id = 'oxford-app-id'
app_key = 'oxford-app-key'
language = 'en'
word_id = sys.argv[1]
# Function to get the definition of a word
def getPronunciation(lexicalEntry):
# we will default to nothing
default = 'N/A';
# First try to get it from here. It isn't always here, so we will wrap it in
# a try so that this won't catastrophically fail
try:
return lexicalEntry['pronunciations'][0]['phoneticSpelling']
except:
# If we don't find it here, that is fine. We will look somewhere else.
pass
# Try to get the entries
try:
entries = lexicalEntry['entries']
except:
# If this fails then return the default
return default
# Loop through all entries, and checck to see if the pronunciation exists
# there. if not pass on to the next entry
for entry in entries:
try:
return entry['pronunciations'][0]['phoneticSpelling']
except:
pass
# if no entries found it then return the default
return default;
try:
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})
resultStr = 'Key word: ' + word_id + '\n\n'
results = r.json()['results']
for result in results:
lexicalEntries = result['lexicalEntries']
lexicalEntriesStr = ''
for lexicalEntry in lexicalEntries:
entries = lexicalEntry['entries']
lexicalCategoryStr = 'Lexical category: ' + lexicalEntry['lexicalCategory'] + '\n'
pronunciationsStr = 'Pronunciations: ' + getPronunciation(lexicalEntry) + '\n'
textStr = 'Text: ' + lexicalEntry['text'] + '\n'
lexicalEntrieStr = '--------------------------------------------------------\n'
lexicalEntrieStr = lexicalEntrieStr + textStr + pronunciationsStr + lexicalCategoryStr + '\n';
for entry in entries:
senses = entry['senses']
for sense in senses:
if 'definitions' in sense:
definitions = sense['definitions']
definitionStr = ''
for definition in definitions:
definitionStr = '* ' + definitionStr + definition + '\n'
lexicalEntrieStr = lexicalEntrieStr + definitionStr
if 'examples' in sense:
examples = sense['examples']
exampleStr = 'Examples: \n'
for example in examples:
exampleStr = exampleStr + example['text'] + '\n\n'
lexicalEntrieStr = lexicalEntrieStr + exampleStr
lexicalEntriesStr = lexicalEntriesStr + lexicalEntrieStr + '\n'
resultStr = resultStr + lexicalEntriesStr
print(resultStr)
except (KeyboardInterrupt, SystemExit):
print('Opp! Search progressing is cancelled!')
except:
print('Opp! No results')