Archive

Posts Tagged ‘languages’

Google Translate in Python

August 2nd, 2009 admin No comments

I was looking around for an example of how to access Google’s Translation services from Python, and all the examples I found seemed too bloated to me, so I decided to write my own, and managed it in just a few lines of code. Perhaps the Ajax API didn’t exist when others wrote theirs, but it’s certainly much easier now.

So here it is, gtrans.py:

#!/usr/bin/env python
# author: sublime@3euser.com
# usage: gtrans <from_lang> <to_lang> <text>
import sys
import urllib
url = ‘http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=’+urllib.quote(‘ ‘.join(sys.argv[3:]))+’&langpair=’+sys.argv[1]+’%7C’+sys.argv[2]
# Google returns the result string in exactly the same format as a python dictionary, just need to escape ‘null’ values.
transtext = eval(urllib.urlopen(url).read().replace(‘null,’, ‘”",’))
if transtext['responseData']:
print “\n”, transtext['responseData']['translatedText'], “\n”

`

url = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q='+urllib.quote(' '.join(sys.argv[3:]))+'&langpair='+sys.argv[1]+'%7C'+sys.argv[2]

transtext = eval(urllib.urlopen(url).read().replace('null,', '"",'))

if transtext['responseData']:
print "\n", transtext['responseData']['translatedText'], "\n"

`