简介
- 由于项目中需要将国际化字符串导出成Excel表格,所以就写了这么一个脚本,目前只实现了导出字符串、后续会继续实现将Excel合入到项目工程中去
-
该脚本是由Python实现的、主要用到的库是openpyxl操作Excel表格、
042ec9e15de70b28500fa5b9e06883be.jpg
from openpyxl import Workbook
import os
import re
wb = Workbook()
ws = wb.active
ws.title = 'iOSString'
ws.cell(row=1, column=1).value = 'key'
urlList = []
valueList = []
keyList = []
# savepath = input('请输入需要保存的路径:')
def __getfilename(path):
f_list = os.listdir(path)
for i in f_list:
if os.path.splitext(i)[1] == '.lproj':
url = path + '/' + i + '/' + 'Localizable.strings'
urlList.append(url)
valueList.append(os.path.splitext(i)[0])
# TODO:这里应该要用线程控制 目前还不会
for i in f_list:
if i == 'Base.lproj':
url = path + '/' + i + '/' + 'Localizable.strings'
__dealbasefile(url)
# 处理key值 因为后面要遍历查询
def __dealbasefile(path):
with open(path) as f:
context = f.read()
partten = re.compile(r'"(.*)" = "(.*)";')
result = partten.findall(context)
for i in range(len(result)):
ws.cell(row=i + 2, column=1).value = result[i][0]
keyList.append(result[i][0])
for i in range(len(urlList)):
ws.cell(row=1, column=i + 2).value = valueList[i]
__dealExcel(urlList[i], i + 2)
- 该方法主要是用正则表达式检测出key value
def __dealExcel(url, index):
print('当前处理的文件是=',url)
with open(url) as f:
context = f.read()
partten = re.compile(r'"(.*)" = "(.*)";')
result = partten.findall(context)
resultDictionary = {}
for i in range(len(result)):
resultDictionary.setdefault(result[i][0], result[i][1])
for i in range(len(keyList)):
if keyList[i] in resultDictionary:
ws.cell(row=i + 2, column=index).value = resultDictionary[keyList[i]]
else:
print('字典里面没有该key=',keyList[i])
# print(resultDictionary)
wb.save('/Users/tusm/Desktop/douban.xlsx')
- 主函数 input 需要输入项目中字符串的目录
if __name__ == "__main__":
path = input('please input string path:')
__getfilename(path)
后面继续完善
网友评论