Python Wrapper for Google Translate AJAX API.

Few Days Ago, i needed some Non English documents to be translated to English language, for which Google AJAX Language API can be used.

I wrote a small script which got the work done ,and why put it to waste when there is a chance that it can be used by others.

So without further ado, here is the code :), Feel free to use it in any commercial/open source projects

 #By Ashish Yadav, released under WTFPL
 #http://sam.zoy.org/wtfpl/
 # -*- coding: utf-8 -*-

 import sys
 import urllib
 import simplejson

 baseUrl = "http://ajax.googleapis.com/ajax/services/language/translate"

 def getSplits(text,splitLength=4500):
     ''' 
     Translate Api has a limit on length of text(4500 characters) that can be translated at once, 
     '''
     return (text[index:index+splitLength] for index in xrange(0,len(text),splitLength))


 def translate(text,src=' ', to='en'):
     '''
     A Python Wrapper for Google AJAX Language API:
     * Uses Google Language Detection, in cases source language is not provided with the source text
     * Splits up text if it's longer then 4500 characters, as a limit put up by the API
     '''

     params = ({'langpair': '%s|%s' % (src, to),
              'v': '1.0'
              })
     retText=''
     for text in getSplits(text):
             params['q'] = text
             resp = simplejson.load(urllib.urlopen('%s' % (baseUrl), data = urllib.urlencode(params)))
             try:
                     retText += resp['responseData']['translatedText']
             except:
                     raise
     return retText


 def test():
     msg = "      Write something You want to be translated to English,\n"\
         "      Enter ctrl+c to exit"
     print msg
     while True:
         text = raw_input('#>  ')
         retText = translate(text)
         print retText


 if __name__=='__main__':
     try:
         test()
     except KeyboardInterrupt:
         print "\n"
         sys.exit(0)

Python Code Formatting is done using the awesome Python2Html utility

Also present as a recipe on Activestate

Advertisements

About Ashish Yadav

Hey there!!! I am Ashish Yadav, a Geek | Music Lover | Open Web enthusiast | Wannabe entrepreneur. I currently live in Chennai, India and share my thoughts, nifty hacks rather infrequently here with rest of the world. If you like my posts, may I suggest subscribing to the blog to read them as they are written :) . As a part of my day job I enjoy writing ubercool python code, and have loads of fun while at it. Opinions presented here are mine and not to be associated with my employer or anyone else. Opinions presented here are mine and not to be associated with my employer or anyone else.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

One Response to Python Wrapper for Google Translate AJAX API.

  1. Pingback: Python Wrapper for Google Translate AJAX API. « Ashish's Weblog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s