/
cnet_client.py
93 lines (75 loc) · 2.06 KB
/
cnet_client.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
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
import urllib, urllib2
try:
import json
except:
import simplejson as json
API_URL = 'http://conceptnet5.media.mit.edu/data/5.1/'
def lookup(word, absolute=False, limit=None):
if word==None:
print "a term must be specified"
return "{}"
if not limit == None:
limit = "?limit="+str(limit)
else:
limit = ""
if absolute:
url = API_URL + word + limit
else:
url = API_URL + "c/en/" + word + limit
return _get_json(url)
def search(absolute=False, rel=None, start=None, end=None, limit=None):
if rel == None and start == None and end == None:
print "atleast one argument must be specified"
return "{}"
if not rel == None:
if not absolute:
#print rel
rel = "/r/"+rel
rel = "rel="+rel
else:
rel = ""
if not start == None:
if not absolute:
start = "/c/en/"+start
start = "start="+start
else:
start = ""
if not end == None:
if not absolute:
end = "/c/en/"+end
end = "end="+end
else:
end = ""
if not limit == None:
limit = "limit="+str(limit)
else:
limit = ""
url = API_URL + "search?filter=core&"+"&".join([rel,start,end,limit])
return _get_json(url)
def assoc(absolute=False, word=None, filt=None, limit=None):
if word == None:
print "Word needs to be defined."
return "{}"
if not absolute:
word = "/c/en/"+word
if not filt == None:
if not absolute:
filt = "/c/en/"+filt
filt = "filter=" + filt
else:
filt = ""
if not limit == None:
limit = "limit=" + str(limit)
else:
limit = ""
url = API_URL + "assoc" + word + "?"+"&".join([filt,limit])
return _get_json(url)
'''
def old_get_json(*url_parts):
url = API_URL + '/'.join(urllib2.quote(p) for p in url_parts) + '?limit=5'
return json.loads(_get_url(url))
'''
def _get_json(url):
#print url
conn = urllib2.urlopen(url)
return json.loads(conn.read())