wolframalpha_api.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. site_url = 'http://www.wolframalpha.com/input/?{query}'
  16. search_query = ''
  17. api_key = ''
  18. # xpath variables
  19. failure_xpath = '/queryresult[attribute::success="false"]'
  20. answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
  21. # do search-request
  22. def request(query, params):
  23. params['url'] = search_url.format(query=urlencode({'input': query}),
  24. api_key=api_key)
  25. # used in response
  26. global search_query
  27. search_query = query
  28. return params
  29. # replace private user area characters to make text legible
  30. def replace_pua_chars(text):
  31. pua_chars = {u'\uf74c': 'd',
  32. u'\uf74d': u'\u212f',
  33. u'\uf74e': 'i',
  34. u'\uf7d9': '='}
  35. for k, v in pua_chars.iteritems():
  36. text = text.replace(k, v)
  37. return text
  38. # get response from search-request
  39. def response(resp):
  40. results = []
  41. search_results = etree.XML(resp.content)
  42. # return empty array if there are no results
  43. if search_results.xpath(failure_xpath):
  44. return []
  45. # parse answer
  46. answer = search_results.xpath(answer_xpath)
  47. if answer:
  48. answer = replace_pua_chars(answer[0].text)
  49. results.append({'answer': answer})
  50. # result url
  51. result_url = site_url.format(query=urlencode({'i': search_query}))
  52. # append result
  53. results.append({'url': result_url,
  54. 'title': search_query + ' - Wolfram|Alpha'})
  55. return results