h/plugins/gcalc.py

29 lines
782 B
Python
Raw Normal View History

import urllib2
import re
from lxml import html
2010-02-22 17:25:01 +00:00
from util import hook
@hook.command
def calc(inp):
'''.calc <term> -- returns Google Calculator result'''
if not inp:
return calc.__doc__
2010-02-22 17:25:01 +00:00
url = "http://www.google.com/search?q="
request = urllib2.Request(url + urllib2.quote(inp, ''))
request.add_header('User-Agent', 'skybot')
page = urllib2.build_opener().open(request).read()
2010-02-22 17:25:01 +00:00
# ugh, scraping HTML with regexes
m = re.search(r'<h2 class=r style="font-size:138%"><b>(.*?)</b>', page)
2010-02-22 17:25:01 +00:00
if m is None:
return "could not calculate " + inp
2010-02-22 17:25:01 +00:00
result = m.group(1).replace("<font size=-2> </font>",",")
result = result.replace(" &#215; 10<sup>","E").replace("</sup>","")
result = result.replace("\xa0",",")
return result