-
Notifications
You must be signed in to change notification settings - Fork 0
/
dict
executable file
·61 lines (52 loc) · 1.88 KB
/
dict
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
#!/usr/bin/env python
import sys
import json
import urllib
import argparse
from HTMLParser import HTMLParser
def main(provider, args):
""" Entry point """
if not sys.stdin.isatty():
for line in sys.stdin:
args += [line.strip()]
if not args:
args = [raw_input("Enter word to search : ")]
args = map(lambda x: urllib.quote(x.lower()), args)
res = {}
for word in args:
url = get_url(provider) % word
result = json.load(urllib.urlopen(url))
res[word] = extract_definitions(result, provider)
prettyprint(res)
def prettyprint(map):
""" Pretty prints results """
parser = HTMLParser()
print
for word in map:
print "%s:" % urllib.unquote(word)
cnt = 0
for definition in map[word]:
cnt += 1
print " %d - %s" % (cnt, parser.unescape(definition).replace('\n',' ').replace('\r',''))
print
def get_url(provider):
""" Returns the template url per provider """
if provider == "urban":
return 'http://api.urbandictionary.com/v0/define?term=%s'
elif provider == "globsbe":
return 'http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=%s'
def extract_definitions(result, provider):
""" Extracts the definition from a result JSON """
if provider == "urban":
return [ dfn["definition"] for dfn in result["list"] if "definition" in dfn ]
elif provider == "globsbe":
if "tuc" in result and len(result["tuc"]) > 0 and "meanings" in result["tuc"][0]:
return [ dfn["text"] for dfn in result["tuc"][0]["meanings"] ]
else:
return []
if __name__ == '__main__':
ap = argparse.ArgumentParser(description = 'dictionary lookup')
ap.add_argument('--urban', '-u', help='use urban dictionary', dest='urban', action='store_true')
ap.add_argument('words', help='words to lookup', nargs='*')
args = ap.parse_args()
main('urban' if args.urban else 'globsbe', args.words)