用python從項(xiàng)目工程中找出含中文的字符串
定義宏 LS(s)
#define LS(s) NSLocalizedString(s, nil)
定義python目錄配置文件 PathConfig.py
# -*- coding: utf-8 -*-
import os
# 文件路徑
# rub_filepath = '../RubbishCodeDemo'
rub_filepath = '../../Storybook/Storybook'
localstring_csv_filepath = 'localstring.csv'
創(chuàng)建文件 regularReplace.py
通過(guò)他找到項(xiàng)目中的所有的含中文字符串
并生成一個(gè) localstring.csv
的語(yǔ)言對(duì)應(yīng)配置表
第一行是 csv 讀取的時(shí)候 需要取出的key信息
['localstringKey','1','2','3',..]
第一列統(tǒng)一中文key 對(duì)應(yīng)的key:'localstringKey'
第二列 對(duì)應(yīng)的原來(lái)中文內(nèi)容 對(duì)應(yīng)的key:'1'
第三 第四 可以后自己添加對(duì)應(yīng)語(yǔ)言的翻譯 對(duì)應(yīng)的key:'2'
,'3'
,'4'
,.....
# -*- coding: utf-8 -*-
import os
import time
import random
import PathConfig
import re
import csv
# 正則查找替換中文字符串
# 排重
csvKeyList = []
csvList = []
def csvWrite():
# csv文件讀寫(xiě)
csvFile = open(PathConfig.localstring_csv_filepath, 'w')
csv_writer = csv.writer(csvFile)
csv_writer.writerow(['localstringKey','1'])
csv_writer.writerow(['語(yǔ)言','中文'])
for csvDic in csvList:
key = csvDic['key']
value = csvDic['value']
csv_writer.writerow([key,value])
csvFile.close()
def replaceStr(content, oldstr, newstr):
replacements = {oldstr:newstr}
for src, target in replacements.iteritems():
content = content.replace(src, target)
return content
def traverse(file_dir):
fs = os.listdir(file_dir)
for dir in fs:
if dir.startswith('.'):
#過(guò)濾隱藏
continue
tmp_path = os.path.join(file_dir, dir)
if not os.path.isdir(tmp_path):
if not dir.endswith('.h') and not dir.endswith('.m'):
continue
with open(tmp_path) as f:
file_str = f.read()
content = file_str.decode('utf-8')
pat = u'(@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?")'
results = re.findall(pat,content)
for s in results:
sn_str = s.encode('utf-8')
new_sn_str = 'LS(%s)'%(sn_str)
# 字符串替換
file_str = file_str.replace(new_sn_str,sn_str)
file_str = file_str.replace(sn_str,new_sn_str)
sn_s = sn_str[2:-1]
if sn_s not in csvKeyList:
csvKeyList.append(sn_s)
csvList.append({'key':sn_s,'value':sn_s})
print '"%s" = "%s";' % (sn_s,sn_s)
with open(tmp_path, 'w') as f:
f.write(file_str)
else:
# 是文件夾,則遞歸調(diào)用
traverse(tmp_path)
def main():
traverse(PathConfig.rub_filepath)
csvWrite()
print('Finish done')
if __name__ == '__main__':
main()
創(chuàng)建 CSVLocalStringRead.py
讀取本地出來(lái)好的本地化語(yǔ)言csv文件
打印中對(duì)應(yīng)語(yǔ)言的 key 和 value 映射
對(duì)應(yīng)復(fù)制到項(xiàng)目的Localizable.strings
文件中
# -*- coding: utf-8 -*-
import os
import csv
import PathConfig
import re
def main():
csvFile = open(PathConfig.localstring_csv_filepath, 'r')
csv_list = []
csv_reader = csv.DictReader(csvFile)
rowCount = len(csv_reader.fieldnames)
for row in csv_reader:
csv_list.append(row)
csvFile.close()
for i in range(rowCount):
if i == 0:
continue
print '\n\n\n\n\n\n\n\n ================================ %s \n\n\n\n\n\n' % str(i)
for row in csv_list:
index = str(i)
key_s = row['localstringKey']
value_s = row[index]
oc_s = '"%s" = "%s";' % (key_s,value_s)
print oc_s
print('Finish done')
if __name__ == '__main__':
main()