wolframalpha_api.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 = ''
  16. # do search-request
  17. def request(query, params):
  18. params['url'] = search_url.format(query=urlencode({'input': query}),
  19. api_key=api_key)
  20. return params
  21. # replace private user area characters to make text legible
  22. def replace_pua_chars(text):
  23. pua_chars = {u'\uf74c': 'd',
  24. u'\uf74d': u'\u212f',
  25. u'\uf74e': 'i',
  26. u'\uf7d9': '='}
  27. for k, v in pua_chars.iteritems():
  28. text = text.replace(k, v)
  29. return text
  30. # get response from search-request
  31. def response(resp):
  32. results = []
  33. search_results = etree.XML(resp.content)
  34. # return empty array if there are no results
  35. if search_results.xpath('/queryresult[attribute::success="false"]'):
  36. return []
  37. # parse answer
  38. answer = search_results.xpath('//pod[attribute::primary="true"]/subpod/plaintext')
  39. if not answer:
  40. return results
  41. answer = replace_pua_chars(answer[0].text)
  42. # append result
  43. # TODO: shouldn't it bind the source too?
  44. results.append({'answer': answer})
  45. # return results
  46. return results