Public » Miscellaneous » Twenty
Clone URL:  
Pushed to one repository · View In Graph Contained in tip

add more magic and switch to Unix line endings

Changeset 83feb398eb90

Parent 541a2f0d76cd

by Profile picture of Benjamin PollackBenjamin Pollack

Changes to one file · Browse files at 83feb398eb90 Showing diff from parent 541a2f0d76cd Diff from another changeset...

Change 1 of 1 Show Entire File magic.py Stacked
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
@@ -1,24 +1,44 @@
-import json -import os -import urllib -import urllib2 - -def image_of(thing): - try: - os.mkdir('images') - except OSError as e: - if e.errno != 17: - raise - try: - j = json.load(urllib2.urlopen('http://api.duckduckgo.com/?q=%s&format=json' % urllib.quote(thing))) - image_url = j['Image'] - if not image_url: - return None - image_path = 'images/%s' % image_url.split('/')[-1] - if not os.path.exists(image_path): - data = urllib2.urlopen(image_url).read() - with open(image_path, 'wb') as f: - f.write(data) - return image_path - except (OSError,): - return None +import json +import os +import re +import urllib +import urllib2 +import webbrowser + +def _resolve_thing(thing): + try: + j = json.load(urllib2.urlopen('http://api.duckduckgo.com/?q=%s&format=json&skip_disambig=1' % urllib.quote(thing))) + return j + except (ValueError, OSError): + return None + +def tell_me_about(thing): + """tries to tell you a little bit about whatever you want""" + j = _resolve_thing(thing) + if not j: + return None + return j['Answer'] or j['Definition'] or j['AbstractText'] + +def take_me_to(thing): + """takes you to a webpage on the appropriate topic""" + j = _resolve_thing(thing) + if j and j['AbstractURL']: + webbrowser.open(j['AbstractURL']) + +def image_of(thing): + """downloads an iamge of whatever you want, saves it, and tells you where it saved""" + try: + os.mkdir('images') + except OSError as e: + if e.errno != 17: + raise + j = _resolve_thing(thing) + image_url = j['Image'] + if not image_url: + return None + image_path = 'images/%s' % re.sub(r'[/\\.?!]', '-', thing).lower().strip() + '.' + image_url.split('.')[-1] + if not os.path.exists(image_path): + data = urllib2.urlopen(image_url).read() + with open(image_path, 'wb') as f: + f.write(data) + return image_path