Consuming Google Translate API with Python

Google just released the beta version of the Python API Client  for their APIs – http://code.google.com/p/google-api-python-client. Just to try how does it works here a very short example for a command line translator from italian to english.

The result is a simple program that in input takes an Italian sentence and writes in output the English translation.

#>python translate.py 'nel mezzo del cammin di nostra vita'
Your [nel mezzo del cammin di nostra vita] is
... [in the middle of the journey of our life]

To write this simple program you have to install the Python API – http://code.google.com/p/google-api-python-client/wiki/Installation. After just create a new file translate.py and copy and paste the following code


#!/usr/bin/python2.4
# -*- coding: utf-8 -*-

“””Italian to English Translate API exaple
“””

__author__ = ‘giulio.roggero@gmail.com’

from apiclient.discovery import build

import pprint
import getopt
import argparse
import json

def main():

parser = argparse.ArgumentParser()
parser.add_argument(‘words’)

args = parser.parse_args()
print “Your [” + args.words + “] is”

service = build(‘translate’, ‘v2′,
developerKey=’AIzaSyDKIH5TfJKNjtbknd-KUZvRrBJA7DXKy40′)
jsonres = service.translations().list( source=’it’, target=’en’, q=[args.words]).execute()

print “… [” + jsonres[‘translations’][0][‘translatedText’] + “]”

if __name__ == ‘__main__’:
main()

Please update the developerKey with your dev key activating the API in the API Console – https://code.google.com/apis/console

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 )

Facebook photo

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

Connecting to %s