wolframalpha_api.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Wolfram Alpha (Maths)
  2. #
  3. # @website http://www.wolframalpha.com
  4. # @provide-api yes (http://api.wolframalpha.com/v2/)
  5. #
  6. # @using-api yes
  7. # @results XML
  8. # @stable yes
  9. # @parse result
  10. from urllib import urlencode
  11. from lxml import etree
  12. # search-url
  13. base_url = 'http://api.wolframalpha.com/v2/query'
  14. search_url = base_url + '?appid={api_key}&{query}&format=plaintext'
  15. api_key = '' # defined in settings.yml
  16. # xpath variables
  17. failure_xpath = '/queryresult[attribute::success="false"]'
  18. answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
  19. # do search-request
  20. def request(query, params):
  21. params['url'] = search_url.format(query=urlencode({'input': query}),
  22. api_key=api_key)
  23. return params
  24. # replace private user area characters to make text legible
  25. def replace_pua_chars(text):
  26. pua_chars = {u'\uf74c': 'd',
  27. u'\uf74d': u'\u212f',
  28. u'\uf74e': 'i',
  29. u'\uf7d9': '='}
  30. for k, v in pua_chars.iteritems():
  31. text = text.replace(k, v)
  32. return text
  33. # get response from search-request
  34. def response(resp):
  35. results = []
  36. search_results = etree.XML(resp.content)
  37. # return empty array if there are no results
  38. if search_results.xpath(failure_xpath):
  39. return []
  40. # parse answer
  41. answer = search_results.xpath(answer_xpath)
  42. if answer:
  43. answer = replace_pua_chars(answer[0].text)
  44. results.append({'answer': answer})
  45. # TODO: append a result with title and link, like in the no api version
  46. return results