使用Python脚本处理OC中的中文字符串
由于Xcode对中文支持良好,所以在开发过程中经常直接使用中文字符串。不过苹果推荐多语言化,需要为中文字符串添加个NSLocalizedString宏。
#!/usr/bin/python# -*- coding: utf-8 -*-'''Localization The Objective-C Code@"..."-->NSLocalizedString(@"...", nil)Jason Lee 2012-03-01'''import os, sysimport reimport codecstargetPattern = re.compile('@"[^"]+"')global newFile, newFilePointerdef isChineseCharacter(ch):return 0x4e00 <= ord(ch) <= 0x9fa5def hasChineseCharacter(str):for char in str:if isChineseCharacter(char):return Truereturn Falsedef buildNewString(oldStr):newStrPrefix = 'NSLocalizedString('newStrSuffix = ', nil)'newStr = newStrPrefix + oldStr + newStrSuffixreturn newStrdef processLine(line):global newFile, newFilePointermatchResult = targetPattern.findall(line)for result in matchResult:if hasChineseCharacter(result):#print result, buildNewString(result)p = re.compile(result)line = p.sub(buildNewString(result), line)newFilePointer.write(line)def processFile(filename):#Xcode file is saved with utf-8global newFile, newFilePointernewFile = 'Replaced.' + filenamenewFilePointer = codecs.open(newFile, 'wb', 'utf-8')fp = codecs.open(filename, 'rb', 'utf-8')for line in fp:processLine(line)fp.close()newFilePointer.close()oldFile = 'Old.' + filenameos.system('mv ' + filename + ' ' + oldFile)os.system('mv ' + newFile + ' ' + filename)#os.system('rm -f ' + oldFile)if __name__ == "__main__":if len(sys.argv) > 1:output = os.popen('ls ' + sys.argv).read()filelist = re.split('\n', output)filelist = filelist[:-1]#print filelistprint 'Localizing...'for file in filelist:if os.path.exists(file):try:#print 'Processing File :', fileprocessFile(file)except Exception as e:print eprint 'Localization Done.'
之后需要做的事情参考:http://blog.csdn.net/jasonblog/article/details/7299544
代码没用经过严格验证,请慎用。起码,没有检查该字符串是否已经加了NSLocalizedString宏。
:)
页:
[1]