Created
September 23, 2009 04:50
-
-
Save arnaudsj/191731 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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