wolframalpha_noapi.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # WolframAlpha (Maths)
  2. #
  3. # @website http://www.wolframalpha.com/
  4. #
  5. # @using-api no
  6. # @results HTML
  7. # @stable no
  8. # @parse answer
  9. import re
  10. import json
  11. from urllib import urlencode
  12. # search-url
  13. url = 'http://www.wolframalpha.com/'
  14. search_url = url+'input/?{query}'
  15. # do search-request
  16. def request(query, params):
  17. params['url'] = search_url.format(query=urlencode({'i': query}))
  18. return params
  19. # get response from search-request
  20. def response(resp):
  21. results = []
  22. # the answer is inside a js function
  23. # answer can be located in different 'pods', although by default it should be in pod_0200
  24. possible_locations = ['pod_0200\.push(.*)\n',
  25. 'pod_0100\.push(.*)\n']
  26. # get line that matches the pattern
  27. for pattern in possible_locations:
  28. try:
  29. line = re.search(pattern, resp.text).group(1)
  30. break
  31. except AttributeError:
  32. continue
  33. if not line:
  34. return results
  35. # extract answer from json
  36. answer = line[line.find('{'):line.rfind('}')+1]
  37. answer = json.loads(answer.encode('unicode-escape'))
  38. answer = answer['stringified'].decode('unicode-escape')
  39. results.append({'answer': answer})
  40. return results