wolframalpha_api.py 1.5 KB

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