Skip to content

Instantly share code, notes, and snippets.

@lxneng
Created April 7, 2010 14:12
Show Gist options
  • Select an option

  • Save lxneng/358922 to your computer and use it in GitHub Desktop.

Select an option

Save lxneng/358922 to your computer and use it in GitHub Desktop.
google translator
class Translator(object):
translate_url = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=%(message)s&langpair=%(from)s%%7C%(to)s"
def __init__(self):
self.browser = Browser()
def translate(self, message, lang_to='en', lang_from=''):
"""
Given a 'message' translate it from 'lang_from' to 'lang_to'.
If 'lang_from' is empty, auto-detects the language.
Returns the translated message.
"""
if lang_to not in _languages:
raise TranslationError, "Language %s is not supported as lang_to." % lang_to
if lang_from not in _languages and lang_from != '':
raise TranslationError, "Language %s is not supported as lang_from." % lang_from
message = quote_plus(message)
real_url = Translator.translate_url % { 'message': message,
'from': lang_from,
'to': lang_to }
try:
translation = self.browser.get_page(real_url)
data = json.loads(translation)
if data['responseStatus'] != 200:
raise TranslationError, "Failed translating: %s" % data['responseDetails']
return data['responseData']['translatedText']
except BrowserError, e:
raise TranslationError, "Failed translating (getting %s failed): %s" % (e.url, e.error)
except ValueError, e:
raise TranslationError, "Failed translating (json failed): %s" % e.message
except KeyError, e:
raise TranslationError, "Failed translating, response didn't contain the translation"
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment