Created
January 31, 2011 01:49
-
-
Save e000/803522 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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