Skip to content

Instantly share code, notes, and snippets.

@arnaudsj
Created September 23, 2009 04:50
Show Gist options
  • Save arnaudsj/191731 to your computer and use it in GitHub Desktop.
Save arnaudsj/191731 to your computer and use it in GitHub Desktop.
# coding=utf-8
# Google async translate demo using Tornado
# Author: Sébastien Arnaud (arnaudsj@gmail.com)
# License: Creative Commons Attribution-Share Alike 3.0 United States License (http://creativecommons.org/licenses/by-sa/3.0/us).
import tornado.httpclient as httpclient
import tornado.ioloop as ioloop
import urllib
import simplejson as json
def handle_response(response):
if response.error:
print "Error:", response.error
result = None
else:
result = response.body
# Stop the async IO loop
ioloop.IOLoop.instance().stop()
# Display the result if any
if result!=None:
translation = json.loads(result)
print "text was translated as %s and means: %s" % (translation[1],translation[0])
def translate(text, target_language):
# Use Google translate
google_translate_url = "http://www.translate.google.com/translate_a/t"
google_translate_params = urllib.urlencode({'client':'t', 'sl':'auto','tl':target_language,'text':text.encode('utf-8')})
# Build and fire the Async request
http_client = httpclient.AsyncHTTPClient()
http_req = httpclient.HTTPRequest( "%s?%s" % (google_translate_url, google_translate_params) , method="GET")
http_client.fetch(http_req, handle_response)
# Start the async IO loop
ioloop.IOLoop.instance().start()
if __name__=="__main__":
target_language = "en"
text = u"Je suis un méchant loup."
translate(text, target_language)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment