|
@@ -14,14 +14,24 @@ from lxml import etree
|
14
|
14
|
# search-url
|
15
|
15
|
base_url = 'http://api.wolframalpha.com/v2/query'
|
16
|
16
|
search_url = base_url + '?appid={api_key}&{query}&format=plaintext'
|
|
17
|
+site_url = 'http://www.wolframalpha.com/input/?{query}'
|
|
18
|
+search_query = ''
|
17
|
19
|
api_key = ''
|
18
|
20
|
|
|
21
|
+# xpath variables
|
|
22
|
+failure_xpath = '/queryresult[attribute::success="false"]'
|
|
23
|
+answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
|
|
24
|
+
|
19
|
25
|
|
20
|
26
|
# do search-request
|
21
|
27
|
def request(query, params):
|
22
|
28
|
params['url'] = search_url.format(query=urlencode({'input': query}),
|
23
|
29
|
api_key=api_key)
|
24
|
30
|
|
|
31
|
+ # used in response
|
|
32
|
+ global search_query
|
|
33
|
+ search_query = query
|
|
34
|
+
|
25
|
35
|
return params
|
26
|
36
|
|
27
|
37
|
|
|
@@ -45,19 +55,21 @@ def response(resp):
|
45
|
55
|
search_results = etree.XML(resp.content)
|
46
|
56
|
|
47
|
57
|
# return empty array if there are no results
|
48
|
|
- if search_results.xpath('/queryresult[attribute::success="false"]'):
|
|
58
|
+ if search_results.xpath(failure_xpath):
|
49
|
59
|
return []
|
50
|
60
|
|
51
|
61
|
# parse answer
|
52
|
|
- answer = search_results.xpath('//pod[attribute::primary="true"]/subpod/plaintext')
|
53
|
|
- if not answer:
|
54
|
|
- return results
|
|
62
|
+ answer = search_results.xpath(answer_xpath)
|
|
63
|
+ if answer:
|
|
64
|
+ answer = replace_pua_chars(answer[0].text)
|
|
65
|
+
|
|
66
|
+ results.append({'answer': answer})
|
55
|
67
|
|
56
|
|
- answer = replace_pua_chars(answer[0].text)
|
|
68
|
+ # result url
|
|
69
|
+ result_url = site_url.format(query=urlencode({'i': search_query}))
|
57
|
70
|
|
58
|
71
|
# append result
|
59
|
|
- # TODO: shouldn't it bind the source too?
|
60
|
|
- results.append({'answer': answer})
|
|
72
|
+ results.append({'url': result_url,
|
|
73
|
+ 'title': search_query + ' - Wolfram|Alpha'})
|
61
|
74
|
|
62
|
|
- # return results
|
63
|
75
|
return results
|