How to use json google translate api?

I am trying to use google translate from python with utf-8 text. What can I call json api? They have a document to embed it in html, but I can not find a suitable API or wsdl anywhere.

Thanks Raphael

+3
json python api google-translate
Jul 16 '09 at 10:03
source share
4 answers

Here is the code that finally works for me. Using a website without an ajax api can result in banning your ip, so this is better.

#!/usr/bin/env python from urllib2 import urlopen from urllib import urlencode import urllib2 import urllib import simplejson import sys # The google translate API can be found here: # http://code.google.com/apis/ajaxlanguage/documentation/#Examples def translate(text = 'hola querida'): tl="es" sl="en" langpair='%s|%s'%(tl,sl) base_url='http://ajax.googleapis.com/ajax/services/language/translate?' data = urllib.urlencode({'v':1.0,'ie': 'UTF8', 'q': text.encode('utf-8'), 'langpair':langpair}) url = base_url+data search_results = urllib.urlopen(url) json = simplejson.loads(search_results.read()) result = json['responseData']['translatedText'] return result 
+7
Jul 16 '09 at 14:02
source share

Use xgoogle from Peteris Kramins ( His blog )

 >>> from xgoogle.translate import Translator >>> >>> translate = Translator().translate >>> >>> print translate("Mani sauc Pēteris", lang_to="en") My name is Peter >>> >>> print translate("Mani sauc Pēteris", lang_to="ru").encode('utf-8')    >>> >>> print translate("  ") My name is Peter 
+2
May 01 '11 at 6:37 a.m.
source share

See what I found: http://code.google.com/intl/en/apis/ajaxlanguage/terms.html

Here is the interesting part:

You will not and will not allow your end users or third parties: .... * send any request longer than 5000 characters; ....

+1
Mar 25 '10 at 18:57
source share

I think you are talking about the ajax api http://code.google.com/apis/ajaxlanguage/ that should be used from javascript, so I don't understand what you mean by "google translate from python"

Alternatively, if you need to use the translation functionality from python, you can directly request the translation page and parse it using xml / html libs, for example. beautiful soup, html5lib

Actually I did it once and the beautiful soup didn’t work on google translate, but html5lib ( http://code.google.com/p/html5lib/ ) did

you will need to do something like this (copied from my larger code base)

 def translate(text, tlan, slan="en"): opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'translate.py/0.1')] htmlPage = opener.open( "http://translate.google.com/translate_t?" + urllib.urlencode({'sl': slan, 'tl':tlan}), data=urllib.urlencode({'hl': 'en', 'ie': 'UTF8', 'text': text.encode('utf-8'), 'sl': slan, 'tl': tlan}) ) parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("etree", cElementTree)) etree_document = parser.parse(htmlPage) return _getResult(etree_document) 
0
Jul 16 '09 at 11:16
source share



All Articles