Changeset 83feb398eb90…
Parent 541a2f0d76cd…
by Benjamin Pollack
Changes to one file · Browse files at 83feb398eb90 Showing diff from parent 541a2f0d76cd Diff from another changeset...
@@ -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
|
Loading...