-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWordDefiner.py
64 lines (43 loc) · 1.6 KB
/
WordDefiner.py
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
__author__ = 'Isaac Wang'
import urllib.request
import urllib.parse
import re
import xml.etree.ElementTree as ET
class WordDefiner:
API_KEY = '564b7dde-f126-44cc-b784-5c7b99d2a384'
def __init__(self):
pass
def query_definition(self, word):
if word is None:
return ''
request = self.make_request(word, WordDefiner.API_KEY)
response = urllib.request.urlopen(request)
return self.parse_definition(str(response.read(), 'utf-8'))
def make_request(self, word, key):
if word is None:
return ''
request = 'http://www.dictionaryapi.com/api/v1/references/collegiate/xml/'
request += urllib.parse.quote(word.strip()) # Change special characters into escape sequences
request += '?key='
request += urllib.parse.quote(key.strip())
return request
def parse_definition(self, xml):
definition_list = []
root = ET.fromstring(xml)
# Find suggestions
if root.find('suggestion'):
return None # Could not find word
for entry in root.findall('entry'):
for definition in entry.findall('def'):
for dt in entry.findall('dt'):
text = dt.text
# PARSE AND PUSH THE DEFINITION
if len(definition_list) == 0:
return None
return definition_list
if __name__ == '__main__':
my_definer = WordDefiner()
request = my_definer.make_request('transition', my_definer.API_KEY)
print(request)
response = my_definer.query_definition('transition')
print(response)