├── .gitignore ├── LICENSE ├── LocalizeString.py └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 leo 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LocalizeString.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """ 4 | 搜索并翻译未处理文字,有两种翻译方式一种是百度翻译,一种是tool.lu在线工具翻译 5 | """ 6 | 7 | import os 8 | import glob 9 | import re 10 | import sys 11 | import getopt 12 | import requests 13 | import random 14 | import hashlib 15 | import time 16 | import uniout 17 | 18 | 19 | # 默认项目路径和搜索路径,搜索路径是项目路径的相对路径 20 | DEFAULT_ROJECT_PATH = 'xxxx' 21 | DEFAULT_SEARCH_PATH = 'xxxx' 22 | # 过滤文件目录(相对路径),过滤文件 23 | Filter_DIRS = ['xxxx'] 24 | Filter_FILES = ['xxxx.m', 25 | 'xxxx.h'] 26 | # 语言文件 27 | LOCALIZE_STRING_FILE_NAME = 'xxxx.strings' 28 | # 百度翻译 29 | APP_ID = '' 30 | SECRET_KEY = '' 31 | # 自动添加 .localized 32 | IS_AUTO_HANDLE = False 33 | # 正则表达式(匹配需要翻译的汉字) 34 | String_PATTERN = u'(' \ 35 | + u'(? 1: 149 | return string[1:] 150 | else: 151 | return string 152 | 153 | 154 | def sub_quote_symbol(string): 155 | """ 156 | 去掉两端冒号 157 | """ 158 | if len(string) > 2: 159 | return string[1:-1] 160 | else: 161 | return string 162 | 163 | 164 | def create_file_model(path): 165 | """ 166 | 创建FileModel 167 | """ 168 | file_object = open(path, 'rb') 169 | file_model = FileModel(path) 170 | try: 171 | line = 0 172 | skip_line = 0 173 | while 1: 174 | line_text = file_object.readline() 175 | if not line_text: 176 | break 177 | line += 1 178 | # 过滤/* */注释 179 | if re.match('^(/\*).*', line_text.lstrip()): 180 | skip_line += 1 181 | if skip_line > 0: 182 | if re.match('.*(\*/)$', line_text.lstrip()): 183 | skip_line -= 1 184 | continue 185 | # 过滤这行 186 | if if_filter_the_line(line_text): 187 | continue 188 | line_text = unicode(line_text, 'utf-8') 189 | for m in re.finditer(String_PATTERN, line_text): 190 | text = sub_at_symbol(m.group().encode("utf-8")) 191 | file_model.texts.append(text) 192 | file_model.finds.append(TextModel(text, line, m)) 193 | finally: 194 | file_object.close() 195 | if not len(file_model.finds) == 0: 196 | print('\n%s' % path) 197 | for text_model in file_model.finds: 198 | print ("有未处理翻译字符在第 %s行 [%s]" % (str(text_model.line).center(5), text_model.text)) 199 | return file_model 200 | 201 | 202 | def filter_exist_localized_string(path, strings): 203 | """ 204 | 过滤已经翻译过的 205 | """ 206 | file_object = open(path, 'rb') 207 | strings = list(set(strings)) 208 | try: 209 | while 1: 210 | line = file_object.readline() 211 | if not line: 212 | break 213 | for string in strings: 214 | if string not in line: 215 | continue 216 | strings.remove(string) 217 | finally: 218 | file_object.close() 219 | return strings 220 | 221 | 222 | def baidu_translate_chinese_string(string): 223 | """ 224 | 翻译成繁体-百度翻译 225 | """ 226 | url = 'http://api.fanyi.baidu.com/api/trans/vip/translate' 227 | salt = random.randint(32768, 65536) 228 | sign = APP_ID + string + str(salt) + SECRET_KEY 229 | m1 = hashlib.md5() 230 | m1.update(sign) 231 | sign = m1.hexdigest() 232 | params = dict() 233 | params['appid'] = APP_ID 234 | params['q'] = string 235 | params['from'] = 'zh' 236 | params['to'] = 'cht' 237 | params['salt'] = salt 238 | params['sign'] = sign 239 | 240 | r = requests.get(url, params) 241 | return r.json()['trans_result'][0]['dst'].encode("utf-8") 242 | 243 | 244 | def tool_lu_translate_chinese_string(string, retry=0): 245 | """ 246 | 翻译成繁体-tool.lu在线工具 247 | """ 248 | if retry == 3: 249 | print "实在等不了,过会再试试吧!" 250 | exit() 251 | url = 'https://tool.lu/zhconvert/ajax.html' 252 | params = dict() 253 | params['code'] = string 254 | params['operate'] = 'zh-hk' 255 | r = requests.post(url, params) 256 | if not r.json() is None: 257 | return r.json()['text'].encode("utf-8") 258 | else: 259 | print "太快啦,慢一点?2秒后我再试试" 260 | time.sleep(2) 261 | return tool_lu_translate_chinese_string(string, retry+1) 262 | 263 | 264 | def composing_line_string(string1, string2): 265 | """ 266 | 组装文字 267 | """ 268 | return "\"" + string1 + "\"" + "=" + "\"" + string2 + "\"" + ";\n" 269 | 270 | 271 | def write_chinese_string(path, string): 272 | """ 273 | 写入文字 274 | """ 275 | with open(path, mode="a") as data: 276 | data.write(string) 277 | 278 | 279 | def auto_handle_localized(filemodel): 280 | """ 281 | 自动添加 '.localized' 282 | """ 283 | with open(filemodel.path, 'r') as f: 284 | lines = f.readlines() 285 | with open(filemodel.path, 'w') as f_w: 286 | line = 0 287 | for line_text in lines: 288 | line += 1 289 | offset = 0 290 | unicode_line = unicode(line_text, 'utf-8') 291 | for text_model in filemodel.finds: 292 | if text_model.line == line: 293 | end = text_model.match.end() + offset 294 | offset += len(u'.localized') 295 | tmp = list(unicode_line)[:end] + list(u'.localized') + list(unicode_line)[end:] 296 | unicode_line = ''.join(tmp) 297 | f_w.write(unicode_line.encode('utf-8')) 298 | 299 | 300 | def get_project_search_path(): 301 | """ 302 | 获取项目路径和搜索路径 303 | 默认项目路径不存在情况下使用脚本所在路径搜索 304 | 如果指定了项目路径使用指定的项目路径 305 | """ 306 | opts, args = getopt.getopt(sys.argv[1:], "vhp:s:") 307 | path1 = DEFAULT_ROJECT_PATH 308 | if not os.path.exists(path1): 309 | path1 = sys.path[0] 310 | path2 = DEFAULT_SEARCH_PATH 311 | if not (path1 in path2): 312 | path2 = path1+path2 313 | if not os.path.exists(path2): 314 | path2 = "" 315 | for op, value in opts: 316 | if op == "-p": 317 | path1 = value 318 | elif op == "-s": 319 | path2 = value 320 | elif op == "-v": 321 | print ("1.0.0") 322 | sys.exit() 323 | elif op == "-h": 324 | print ("\t-p\t项目路径 \n\t-s\t搜索路径(可以是文件,也可以是目录)") 325 | sys.exit() 326 | # 如果搜索路径不是绝对路径,补充完整 327 | if not (path1 in path2): 328 | path2 = path1 + path2 329 | return path1, path2 330 | 331 | 332 | if __name__ == "__main__": 333 | 334 | project_path, search_path = get_project_search_path() 335 | 336 | if not os.path.exists(project_path): 337 | print ("请检查项目路径:%s是否正确" % project_path) 338 | exit() 339 | if not os.path.exists(search_path): 340 | print ("请检查搜索路径:%s是否正确" % search_path) 341 | exit() 342 | 343 | zh_localize_path = get_localize_file_by_type(project_path, 'zh-Hans') 344 | hk_localize_path = get_localize_file_by_type(project_path, 'zh-Hant-HK') 345 | 346 | if zh_localize_path is None or hk_localize_path is None: 347 | print ("请检查 LOCALIZE_STRING_FILE_NAME 参数") 348 | exit() 349 | 350 | print("开始搜索未翻译文案") 351 | 352 | untreated_files = list() 353 | wait_translates = list() 354 | 355 | for filepath in find_all_source_files(search_path): 356 | untreated_file_model = create_file_model(filepath) 357 | if len(untreated_file_model.texts) == 0: 358 | continue 359 | wait_translates += untreated_file_model.texts 360 | untreated_files.append(untreated_file_model) 361 | 362 | if len(untreated_files) == 0: 363 | print ("\n没有需要处理的文字") 364 | exit() 365 | 366 | wait_translates = filter_exist_localized_string(zh_localize_path, wait_translates) 367 | 368 | if not len(wait_translates) == 0: 369 | num = 0 370 | print ("\n待翻译文字 %s\n" % wait_translates) 371 | for simplified in wait_translates: 372 | simplified = sub_quote_symbol(simplified) 373 | traditional = tool_lu_translate_chinese_string(simplified) 374 | write_chinese_string(zh_localize_path, composing_line_string(simplified, simplified)) 375 | write_chinese_string(hk_localize_path, composing_line_string(simplified, traditional)) 376 | num += 1 377 | print simplified + "=" + traditional 378 | print ('已翻译 %d/%d' % (num, len(wait_translates))) 379 | print ('\n翻译完成') 380 | else: 381 | print ('\n没有需要翻译的文字') 382 | 383 | if not IS_AUTO_HANDLE: 384 | exit() 385 | 386 | print ('\n开始自动处理\n') 387 | 388 | for untreated_file_model in untreated_files: 389 | print ('正在处理:%s' % os.path.basename(untreated_file_model.path)) 390 | auto_handle_localized(untreated_file_model) 391 | 392 | print ('\n自动处理完成') 393 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LocalizeString-iOS 2 | iOS项目自动国际化脚本 3 | 4 | 找出项目中所有中文字符串文案,并自动翻译成繁体写入到国际化文件中。(不支持xib) 5 | 6 | python依赖 7 | 8 | ``` 9 | pip install requests 10 | pip install uniout 11 | ``` 12 | 13 | 14 | 配置 15 | 16 | `LOCALIZE_STRING_FILE_NAME`(国际化语言文件名) 这个是必须配置的。 17 | 18 | 19 | 使用方法: 20 | 21 | 22 | ```python 23 | python LocalizeString.py -p 项目目录 -s 需要批量翻译的目录 24 | ``` 25 | 26 | 也可以在 `LocalizeString.py` 配置默认参数 27 | 28 | --------------------------------------------------------------------------------