Created
October 25, 2016 04:01
-
-
Save calvingit/9c0ab4d2e2328298d2ca6cfb786648c2 to your computer and use it in GitHub Desktop.
调用Google Translate API 翻译
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
# /usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# 同级目录下面包含 Localizable.strings 或者 InfoPlist.strings,把strings文件的注释都去掉 | |
# cnFile 参数修改需要翻译Localizable还是InfoPlist | |
# 到Google翻译API页面申请Key(https://cloud.google.com/translate/v2/quickstart),送300美刀,免费2个月 | |
# 安装google-api-python-client (https://developers.google.com/api-client-library/python/apis/translate/v2) | |
# pip install --upgrade google-api-python-client | |
# 会自动生成对应的.lproj目录 | |
# 注意: 葡萄牙语、繁体中文的语言缩写分别是pt和zh-TW,这个和Xcode的目录有点区别,其他语言都一样 | |
import sys | |
import os | |
from apiclient.discovery import build | |
# 中文翻译文件 | |
cnFile = 'Localizable' #或者'InfoPlist' | |
# 替换Google翻译Key | |
APIKey = '' | |
def translateChinese(query, destLang): | |
service = (build('translate', 'v2', developerKey=APIKey)) | |
try: | |
request = service.translations().list(q=query, target=destLang) | |
response = request.execute() | |
return response['translations'][0]['translatedText'] | |
except Exception, e: | |
print e | |
finally: | |
return None | |
def writeNewStringsFile(lan): | |
translationsList = [] | |
folder = lan[1] + '.lproj' | |
if not os.path.isdir(folder): | |
os.mkdir(folder) | |
file = open(cnFile + '.strings', 'rb') | |
while 1: | |
lines = file.readlines(100000) | |
if not lines: | |
break | |
for line in lines: | |
line.rstrip("\n") | |
if len(line) < 4: | |
continue | |
tempArray = line.split('=') | |
key = tempArray[0].strip().strip('\"') | |
value = tempArray[1].strip().strip(';\n').strip('\"') | |
translationsList.append((key,value)) | |
file.close() | |
file = open( folder + '/' + cnFile +'.strings', 'w+') | |
for tup in translationsList: | |
ret = translateChinese(tup[1], lan[1]) | |
strings = '\"' + tup[0] + '\"=\"' + ret.capitalize() + '\";\n' | |
strings = strings.decode('UTF-8') | |
print lan[0] + ': ' + strings | |
file.write(strings) | |
file.close() | |
#tuple(中文,Google翻译key缩写) | |
lans = [#('英语', 'en'), | |
('意大利语', 'it'), | |
('日语', 'ja'), | |
('韩语', 'ko'), | |
('法语', 'fr'), | |
('西班牙语', 'es'), | |
('泰语', 'th'), | |
#('阿拉伯语', 'ar'), | |
('俄语', 'ru'), | |
('葡萄牙语', 'pt'), | |
('德语', 'de'), | |
#('荷兰语', 'nl'), | |
#('波兰语', 'pl'), | |
#('保加利亚语', 'bg'), | |
#('爱沙尼亚语', 'et'), | |
#('丹麦语', 'da'), | |
#('芬兰语', 'fi'), | |
#('捷克语', 'cs'), | |
#('罗马尼亚语', 'ro'), | |
#('瑞典语', 'sv'), | |
#('匈牙利语', 'hu'), | |
('繁体中文', 'zh-TW')]; | |
reload(sys) # reload 才能调用 setdefaultencoding 方法 | |
sys.setdefaultencoding('utf-8') # 设置 'utf-8' | |
for lan in lans : | |
writeNewStringsFile(lan) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment