Skip to content

Instantly share code, notes, and snippets.

@e000
Created January 31, 2011 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save e000/803522 to your computer and use it in GitHub Desktop.
Save e000/803522 to your computer and use it in GitHub Desktop.
from urllib import urlencode, urlopen
from xml.etree.cElementTree import fromstring
appId = 'appid'
def search(query, format=('plaintext', )):
return parseWolframAlphaResponse(urllib.urlopen('http://api.wolframalpha.com/v2/query?%s' % (
urlencode(
{
'appid': appId,
'input': query,
'format': ','.join(format)
}
)
)
).read())
def parseWolframAlphaResponse(response, redirected = False):
xmlTree = fromstring(response)
recalculate = xmlTree.get('recalculate')
if recalculate:
if not redirected:
return parseWolframAlphaResponse(urllib.urlopen(recalculate).read(), True)
else:
return 'Error', 'Too many redirects.'
else:
success = xmlTree.get('success')
if success == 'true':
out = []
for pod in xmlTree.findall('pod'):
title = pod.get('title')
plaintext = pod.find('subpod/plaintext')
if plaintext is not None and plaintext.text:
out.append((title, plaintext.text.split('\n')))
return True, out
else:
return False, [tip.get('text') for tip in xmlTree.findall('tips/tip')]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment