wolframalpha_api.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. from re import search
  13. # search-url
  14. base_url = 'http://api.wolframalpha.com/v2/query'
  15. search_url = base_url + '?appid={api_key}&{query}&format=plaintext'
  16. site_url = 'http://www.wolframalpha.com/input/?{query}'
  17. api_key = '' # defined in settings.yml
  18. # xpath variables
  19. failure_xpath = '/queryresult[attribute::success="false"]'
  20. answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
  21. input_xpath = '//pod[starts-with(attribute::title, "Input")]/subpod/plaintext'
  22. # do search-request
  23. def request(query, params):
  24. params['url'] = search_url.format(query=urlencode({'input': query}),
  25. api_key=api_key)
  26. return params
  27. # replace private user area characters to make text legible
  28. def replace_pua_chars(text):
  29. pua_chars = {u'\uf74c': 'd',
  30. u'\uf74d': u'\u212f',
  31. u'\uf74e': 'i',
  32. u'\uf7d9': '='}
  33. for k, v in pua_chars.iteritems():
  34. text = text.replace(k, v)
  35. return text
  36. # get response from search-request
  37. def response(resp):
  38. results = []
  39. search_results = etree.XML(resp.content)
  40. # return empty array if there are no results
  41. if search_results.xpath(failure_xpath):
  42. return []
  43. # parse answers
  44. answers = search_results.xpath(answer_xpath)
  45. if answers:
  46. for answer in answers:
  47. answer = replace_pua_chars(answer.text)
  48. results.append({'answer': answer})
  49. # if there's no input section in search_results, check if answer has the input embedded (before their "=" sign)
  50. try:
  51. query_input = search_results.xpath(input_xpath)[0].text
  52. except IndexError:
  53. query_input = search(u'([^\uf7d9]+)', answers[0].text).group(1)
  54. # append link to site
  55. result_url = site_url.format(query=urlencode({'i': query_input.encode('utf-8')}))
  56. results.append({'url': result_url,
  57. 'title': query_input + " - Wolfram|Alpha"})
  58. return results