Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created August 22, 2012 09:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jugyo/3423990 to your computer and use it in GitHub Desktop.
Save jugyo/3423990 to your computer and use it in GitHub Desktop.
Using Google Translate API in Python
import urllib2
import json
url = 'https://www.googleapis.com/language/translate/v2?key={0}&q={1}&source={2}&target={3}'
def translate(api_key, text, sourcelang, targetlang):
request = urllib2.Request(url.format(api_key.encode('utf-8'), text.encode('utf-8'), sourcelang.encode('utf-8'), targetlang.encode('utf-8')))
response = urllib2.urlopen(request).read()
data = json.loads(response)
return data['data']['translations'][0]['translatedText'].encode('utf-8')
print translate('API-KEY', 'Hello World', 'en', 'ja')
@nicosd
Copy link

nicosd commented Jul 19, 2017

Thanks for the code.
I get a syntax error (Invalid syntax) pointing to print translate(...)

Any ideas?

@josifoski
Copy link

how this will be in python3?

@lemisky
Copy link

lemisky commented Jun 19, 2021

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment