wolframalpha_api.py 1.8 KB

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