美文网首页
iOS 国际化 xib和storyboard 脚本自增

iOS 国际化 xib和storyboard 脚本自增

作者: 夕阳流枫 | 来源:发表于2018-09-21 17:06 被阅读0次

    最近做了一个项目,需要用到国际化,在网上找了很多关于xib和storyboard 自增的解决方式,发现网上的处理方式基本上一致,这里就遇到问题了,我们项目中很多的模块都是分文件存放的,因此发现者就有个缺陷是只能遍历指定路径下的xib或者sb,没有实现递归查询,下面是这次爬坑后进行的修改的脚本代码。

    在这里记录下这次国际化的收获,希望下一次有人遇到同样的问题的时候,能够帮到你

    这里对网络上的名为StoryboardAutoGenStrings.py的脚本进行修改,遍历项目下所有xib及sb文件

    直接上代码:

    #!/usr/bin/env python

    # encoding: utf-8

    """

    StoryboardAutoGenStrings.py

    Created by linyu on 2015-02-13.

    Modified by DarkAngel on 2016-12-02.

    Copyright (c) 2016 DarkAngel. All rights reserved.

    """

    importimp 

    importsys 

    import os

    import glob

    importstring 

    importre 

    import time

    imp.reload(sys) 

    sys.setdefaultencoding('utf-8') #设置默认编码,只能是utf-8,下面\u4e00-\u9fa5要求的

    KSourceFile = 'Base.lproj/*.storyboard'

    KTargetFile = '*.lproj/*.strings' 

    KGenerateStringsFile = 'TempfileOfStoryboardNew.strings'

    ColonRegex = ur'["](.*?)["]'

    KeyParamRegex = ur'["](.*?)["](\s*)=(\s*)["](.*?)["];'

    AnotationRegexPrefix = ur'/(.*?)/'

    defgetCharaset(string_txt):

    filedata = bytearray(string_txt[:4])

    iflen(filedata) <4:

    return 0

    if  (filedata[0] ==0xEF)and(filedata[1] ==0xBB)and(filedata[2] ==0xBF):

    print 'utf-8'

    return 1

    elif(filedata[0] ==0xFF)and(filedata[1] ==0xFE)and(filedata[2] ==0x00)and(filedata[3] ==0x00):

    print 'utf-32/UCS-4,little endian'

    return 3

    elif(filedata[0] ==0x00)and(filedata[1] ==0x00)and(filedata[2] ==0xFE)and(filedata[3] ==0xFF):

    print 'utf-32/UCS-4,big endian'

    return 3

    elif(filedata[0] ==0xFE)and(filedata[1] ==0xFF):

    print 'utf-16/UCS-2,little endian'

    return 2

    elif(filedata[0] ==0xFF)and(filedata[1] ==0xFE):

    print 'utf-16/UCS-2,big endian'

    return 2

    else:

    print 'can not recognize!'

    return 0

    defdecoder(string_txt):

    var  = getCharaset(string_txt)

    ifvar ==1:

    returnstring_txt.decode("utf-8")

    elifvar ==2:

    returnstring_txt.decode("utf-16")

    elifvar ==3:

    returnstring_txt.decode("utf-32")

    else:

    returnstring_txt

    defconstructAnotationRegex(str):

    returnAnotationRegexPrefix +'\n'+ str

    defgetAnotationOfString(string_txt,suffix):

    anotationRegex = constructAnotationRegex(suffix)

    anotationMatch = re.search(anotationRegex,string_txt)

    anotationString =''

    ifanotationMatch:

    match = re.search(AnotationRegexPrefix,anotationMatch.group(0))

    ifmatch:

    anotationString = match.group(0)

    returnanotationString

    defcompareWithFilePath(newStringPath,originalStringPath):

    #read newStringfile 

    nspf=open(newStringPath,"r")

    #newString_txt =  str(nspf.read(5000000)).decode("utf-16")

    newString_txt =  decoder(str(nspf.read(5000000)))

    nspf.close()

    newString_dic = {}

    anotation_dic = {}

    forstfmatchinre.finditer(KeyParamRegex , newString_txt):

    linestr = stfmatch.group(0)

    anotationString = getAnotationOfString(newString_txt,linestr)

    linematchs = re.findall(ColonRegex, linestr)

    iflen(linematchs) ==2:

    leftvalue = linematchs[0]

    rightvalue = linematchs[1]

    newString_dic[leftvalue] = rightvalue

    anotation_dic[leftvalue] = anotationString

    #read originalStringfile 

    ospf=open(originalStringPath,"r")

    originalString_txt =  decoder(str(ospf.read(5000000)))

    ospf.close()

    originalString_dic = {}

    forstfmatchinre.finditer(KeyParamRegex , originalString_txt):

    linestr = stfmatch.group(0)

    linematchs = re.findall(ColonRegex, linestr)

    iflen(linematchs) ==2:

    leftvalue = linematchs[0]

    rightvalue = linematchs[1]

    originalString_dic[leftvalue] = rightvalue

    #compare and remove the useless param in original string

    forkeyinoriginalString_dic:

    if(keynotinnewString_dic):

    keystr ='"%s"'%key

    replacestr ='//'+keystr

    match = re.search(replacestr , originalString_txt)

    ifmatchisNone:

    originalString_txt = originalString_txt.replace(keystr,replacestr)

    #compare and add new param to original string

    executeOnce =1

    forkeyinnewString_dic:

    values = (key, newString_dic[key])

    if(keynotinoriginalString_dic):

    newline =''

    ifexecuteOnce ==1:

    timestamp = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))

    newline ='\n//##################################################################################\n'

    newline +='//#          StoryboardAutoGenStrings        '+timestamp+'\n'

    newline +='//##################################################################################\n'

    executeOnce =0

    newline +='\n'+anotation_dic[key]

    newline +='\n"%s" = "%s";\n'%values

    originalString_txt += newline

    #write into origial file

    sbfw=open(originalStringPath,"w")

    sbfw.write(originalString_txt)

    sbfw.close()

    defextractFileName(file_path):

    seg = file_path.split('/')

    lastindex = len(seg) -1

    returnseg[lastindex]

    defextractFilePrefix(file_path):

    seg = file_path.split('/')

    lastindex = len(seg) -1

    prefix =  seg[lastindex].split('.')[0]

    returnprefix

    defgenerateStoryboardStringsfile(storyboard_path,tempstrings_path):

        #生成临时的strings文件,Mac OS 10.12.1生成的是utf-16格式的,这样在对比时,会报错。 这里利用iconv将 utf-16 转换成 utf-8。

        cmdstring ='ibtool '+storyboard_path+' --generate-strings-file '+tempstrings_path+'temp\n'+'iconv -f utf-16 -t utf-8 '+tempstrings_path+'temp > '+tempstrings_path

        ifos.system(cmdstring) ==0:

            os.remove(tempstrings_path +'temp')

            return1

        else:

            os.remove(tempstrings_path +'temp')

            return0

    defallUIFiles(path):

    s = os.popen("find "+path+" -name \*.xib").read()

    allFiles = []

    foriins.split("\n"):

    ifi !="":

    allFiles.append(i)

    s = os.popen("find "+path+" -name \*.storyboard").read()

    foriins.split("\n"):

    ifi !="":

    allFiles.append(i)

    returnallFiles

    defmain():

    filePath = sys.argv[1]

    allFiles = allUIFiles(filePath)

    forfileinallFiles:

    currentPath = os.path.abspath(os.path.dirname(os.path.dirname(file)))

    sourceFilePath = file 

    sourceFile_list = glob.glob(sourceFilePath)

    iflen(sourceFile_list) ==0:

    print 'error dictionary,you should choose the dic upper the Base.lproj'

    return

    targetFilePath = currentPath +'/'+ KTargetFile

    targetFile_list = glob.glob(targetFilePath)

    tempFile_Path = currentPath +'/'+ KGenerateStringsFile

    iflen(targetFile_list) ==0:

    print 'error framework , no .lproj dic was found'

    return

    forsourcePathinsourceFile_list:

    sourceprefix = extractFilePrefix(sourcePath)

    sourcename = extractFileName(sourcePath)

    print'init with %s'%sourcename

    ifgenerateStoryboardStringsfile(sourcePath,tempFile_Path) ==1:

    print '- - genstrings %s successfully'%sourcename

    fortargetPathintargetFile_list:

    targetprefix = extractFilePrefix(targetPath)

    targetname = extractFileName(targetPath) 

    ifcmp(sourceprefix,targetprefix) ==0:

    print '- - dealing with %s'%targetPath

    compareWithFilePath(tempFile_Path,targetPath)

    print 'finish with %s'%sourcename

    os.remove(tempFile_Path)

    else:

    print '- - genstrings %s error'%sourcename

    if__name__ =='__main__':

    main()


    以上代码是在原作者的技术处加了一个路径查询及循环,

    在项目中添加编译运行脚本

    python ${SRCROOT}/${TAEGET_NAME}LanguageSettingsDemo/Resources/StoryboardAutoGenStrings.py ${SRCROOT}/${TAEGET_NAME}LanguageSettingsDemo/

    感谢  DarkAngel (暗の天使) 作者辛勤的付出与分享

    第一次写爬坑记录,有不足之处见谅,如有侵权,请联系删除

    相关文章

      网友评论

          本文标题:iOS 国际化 xib和storyboard 脚本自增

          本文链接:https://www.haomeiwen.com/subject/wwhznftx.html