Created
March 9, 2010 04:26
-
-
Save csytan/326181 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib | |
import re | |
import uuid | |
from django.utils import simplejson | |
def google_translate(text, source='en', target='fr'): | |
subs = {} | |
for arg in re.findall('(\{.+?\})', text): | |
sub = str(uuid.uuid4()).replace('-', '') | |
subs[sub] = arg | |
text = text.replace(arg, sub) | |
params = urllib.urlencode({ | |
'v': '1.0', | |
'q': text, | |
'langpair': source + '|' + target, | |
'format': 'text' | |
}) | |
opener = urllib.FancyURLopener() | |
opener.addheader('Referer', 'http://www.caterpi.com/') | |
request = opener.open('http://ajax.googleapis.com/ajax/services/language/translate', params) | |
data = simplejson.loads(request.read()) | |
response = data.get('responseData') | |
if response: | |
translation = response.get('translatedText') | |
for sub, arg in subs.items(): | |
translation = translation.replace(sub, arg) | |
return translation | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment