Created
January 10, 2017 19:33
-
-
Save elifiner/86020e9b6dbbe262cf62d76392479300 to your computer and use it in GitHub Desktop.
This file contains 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
# creates localized version of a string using Google Translate | |
import re | |
import json | |
import requests | |
from urllib.parse import quote_plus | |
def translate(text, source, target): | |
url = 'https://translate.googleapis.com/translate_a/single?client=gtx&sl={source}&tl={target}&dt=t&q={text}' | |
r = requests.get(url.format(source=source, target=target, text=text)) | |
data = json.loads(re.sub(',+', ',', r.text)) | |
return data[0][0][0] | |
def localize(text, targets): | |
source = 'en' | |
parts = [] | |
parts.append('[{}:]'.format(source)) | |
parts.append(text) | |
for target in targets: | |
parts.append('[{}:]'.format(target)) | |
parts.append(translate(text, source, target)) | |
parts.append('[:]') | |
return ''.join(parts) | |
print(localize('Hello', ['ru', 'es'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment