1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- from urllib import urlencode
- from lxml import etree
- base_url = 'http://api.wolframalpha.com/v2/query'
- search_url = base_url + '?appid={api_key}&{query}&format=plaintext'
- api_key = ''
- failure_xpath = '/queryresult[attribute::success="false"]'
- answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
- def request(query, params):
- params['url'] = search_url.format(query=urlencode({'input': query}),
- api_key=api_key)
- return params
- def replace_pua_chars(text):
- pua_chars = {u'\uf74c': 'd',
- u'\uf74d': u'\u212f',
- u'\uf74e': 'i',
- u'\uf7d9': '='}
- for k, v in pua_chars.iteritems():
- text = text.replace(k, v)
- return text
- def response(resp):
- results = []
- search_results = etree.XML(resp.content)
-
- if search_results.xpath(failure_xpath):
- return []
-
- answers = search_results.xpath(answer_xpath)
- if answers:
- for answer in answers:
- answer = replace_pua_chars(answer.text)
- results.append({'answer': answer})
-
- return results
|