Asking Google to run a simple langauge translation

27 Sep. 2009

This is Python code for querying Google for a language translation

#!/usr/bin/env python

import urllib
import simplejson
import nltk.data
 
api_url = "http://ajax.googleapis.com/ajax/services/language/translate"
 
def translate(text, src='', to='fr'):
    params = ({'langpair': '%s|%s' % (src, to),
               'v': '1.0'
               })
    target_text=''
    sent_detector = nltk.data.load('tokenizers/punkt/english.pickle')
    for text in sent_detector.tokenize(text.strip()):
        params['q'] = text
        resp = simplejson.load(urllib.urlopen('%s' % (api_url), data =
                                              urllib.urlencode(params)))
        try:
            target_text += resp['responseData']['translatedText'] + " "
        except:
            raise
    return target_text
 
if __name__=='__main__':
    text = """
    Hello Chris. Hello Delip. I am still in my pajamas this morning and
    haven't had ANY coffee yet. But I should be heading out the door with
    my lady in a few minutes to find breakfast (and coffee). I can't decide
    if I want eggs benedict or a toasted bagel with cream cheese and
    salmon. Such is life!
    """
    print "EN :: %s" % (text)
    translated_text = translate(text)
    print "FR :: %s" % (translated_text)