123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122 |
- from urllib import urlencode
- from lxml import etree
- search_url = 'https://api.wolframalpha.com/v2/query?appid={api_key}&{query}'
- site_url = 'https://www.wolframalpha.com/input/?{query}'
- api_key = ''
- failure_xpath = '/queryresult[attribute::success="false"]'
- answer_xpath = '//pod[attribute::primary="true"]/subpod/plaintext'
- input_xpath = '//pod[starts-with(attribute::id, "Input")]/subpod/plaintext'
- pods_xpath = '//pod'
- subpods_xpath = './subpod'
- pod_id_xpath = './@id'
- pod_title_xpath = './@title'
- plaintext_xpath = './plaintext'
- image_xpath = './img'
- img_src_xpath = './@src'
- img_alt_xpath = './@alt'
- image_pods = {'VisualRepresentation',
- 'Illustration'}
- def request(query, params):
- params['url'] = search_url.format(query=urlencode({'input': query}),
- api_key=api_key)
- params['headers']['Referer'] = site_url.format(query=urlencode({'i': query}))
- return params
- def replace_pua_chars(text):
- pua_chars = {u'\uf522': u'\u2192',
- u'\uf7b1': u'\u2115',
- u'\uf7b4': u'\u211a',
- u'\uf7b5': u'\u211d',
- u'\uf7bd': u'\u2124',
- u'\uf74c': 'd',
- u'\uf74d': u'\u212f',
- u'\uf74e': 'i',
- u'\uf7d9': '='}
- for k, v in pua_chars.iteritems():
- text = text.replace(k, v)
- return text
- def response(resp):
- results = []
- search_results = etree.XML(resp.content)
-
- if search_results.xpath(failure_xpath):
- return []
- try:
- infobox_title = search_results.xpath(input_xpath)[0].text
- except:
- infobox_title = None
- pods = search_results.xpath(pods_xpath)
- result_chunks = []
- for pod in pods:
- pod_id = pod.xpath(pod_id_xpath)[0]
- pod_title = pod.xpath(pod_title_xpath)[0]
- subpods = pod.xpath(subpods_xpath)
- if not subpods:
- continue
-
- for subpod in subpods:
- content = subpod.xpath(plaintext_xpath)[0].text
- image = subpod.xpath(image_xpath)
- if content and pod_id not in image_pods:
-
- if not infobox_title:
- infobox_title = content
- content = replace_pua_chars(content)
- result_chunks.append({'label': pod_title, 'value': content})
- elif image:
- result_chunks.append({'label': pod_title,
- 'image': {'src': image[0].xpath(img_src_xpath)[0],
- 'alt': image[0].xpath(img_alt_xpath)[0]}})
- if not result_chunks:
- return []
-
- results.append({'infobox': infobox_title,
- 'attributes': result_chunks,
- 'urls': [{'title': 'Wolfram|Alpha', 'url': resp.request.headers['Referer'].decode('utf8')}]})
-
- results.append({'url': resp.request.headers['Referer'].decode('utf8'),
- 'title': 'Wolfram|Alpha',
- 'content': infobox_title})
- return results
|