Permalink
Browse files

Fixed google calculator using a different method

  • Loading branch information...
BirdAPI committed Apr 11, 2012
1 parent 517f245 commit cabf4fa676a2dc28299fe90f1897c9caef14d113
Showing with 26 additions and 3 deletions.
  1. +1 −1 README.md
  2. +25 −2 google.py
View
@@ -174,7 +174,7 @@ print "dollars -> pesos exchange rate = {0}".format(rate)
dollars -> pesos exchange rate = 13.1580679
```
-Perform your own math. The following 2 statements equal:
+Perform your own math. The following 2 statements are equal:
```python
5.0 * Google.exchange_rate("USD", "EUR")
View
@@ -9,9 +9,13 @@
import urllib2
import sys
import re
+try:
+ import json
+except ImportError:
+ import simplejson as json
__author__ = "Anthony Casagrande <birdapi@gmail.com>"
-__version__ = "0.8"
+__version__ = "0.9"
"""
Represents a standard google search result
@@ -136,7 +140,7 @@ def search(query, pages = 1):
Attempts to use google calculator to calculate the result of expr
"""
@staticmethod
- def calculate(expr):
+ def calculate_old(expr):
url = get_search_url(expr)
html = get_html(url)
if html:
@@ -264,6 +268,25 @@ def convert_currency(amount, from_currency, to_currency):
def exchange_rate(from_currency, to_currency):
return Google.convert_currency(1, from_currency, to_currency)
+ """
+ Attempts to use google calculator to calculate the result of expr
+ """
+ @staticmethod
+ def calculate(expr):
+ conn = httplib.HTTPSConnection("www.google.com")
+ req_url = "/ig/calculator?hl=en&q={0}".format(expr.replace(" ", "%20"))
+ headers = { "User-Agent": "Mozilla/5.001 (windows; U; NT4.0; en-US; rv:1.0) Gecko/25250101" }
+ conn.request("GET", req_url, "", headers)
+ response = conn.getresponse()
+ j = response.read().decode("utf-8").replace(u"\xa0", "")
+ conn.close()
+ j = re.sub(r"{\s*'?(\w)", r'{"\1', j)
+ j = re.sub(r",\s*'?(\w)", r',"\1', j)
+ j = re.sub(r"(\w)'?\s*:", r'\1":', j)
+ j = re.sub(r":\s*'(\w)'\s*([,}])", r':"\1"\2', j)
+ js = json.loads(j)
+ return parse_calc_result(js["lhs"] + " = " + js["rhs"])
+
def normalize_query(query):
return query.strip().replace(":", "%3A").replace("+", "%2B").replace("&", "%26").replace(" ", "+")

0 comments on commit cabf4fa

Please sign in to comment.