Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 使用Python脚本处理OC中的中文字符串

由于Xcode对中文支持良好,所以在开发过程中经常直接使用中文字符串。不过苹果推荐多语言化,需要为中文字符串添加个NSLocalizedString宏。
  1. #!/usr/bin/python   
  2. # -*- coding: utf-8 -*-   
  3.   
  4. """"" 
  5.     Localization The Objective-C Code 
  6.     @"..."  -->  NSLocalizedString(@"...", nil) 
  7.     Jason Lee    2012-03-01 
  8. """  
  9.   
  10. import os, sys  
  11. import re  
  12. import codecs  
  13.   
  14. targetPattern = re.compile("@"[^"]+"")  
  15. global newFile, newFilePointer  
  16.   
  17. def isChineseCharacter(ch):  
  18.     return 0x4e00 <= ord(ch) <= 0x9fa5  
  19.   
  20. def hasChineseCharacter(str):  
  21.     for char in str:  
  22.         if isChineseCharacter(char):  
  23.             return True  
  24.     return False  
  25.   
  26. def buildNewString(oldStr):  
  27.     newStrPrefix = "NSLocalizedString("  
  28.     newStrSuffix = ", nil)"  
  29.     newStr = newStrPrefix + oldStr + newStrSuffix  
  30.     return newStr  
  31.   
  32. def processLine(line):  
  33.     global newFile, newFilePointer  
  34.       
  35.     matchResult = targetPattern.findall(line)  
  36.     for result in matchResult:  
  37.         if hasChineseCharacter(result):  
  38.             #print result, buildNewString(result)   
  39.             p = re.compile(result)  
  40.             line = p.sub(buildNewString(result), line)  
  41.       
  42.     newFilePointer.write(line)  
  43.   
  44. def processFile(filename):  
  45.     #Xcode file is saved with utf-8   
  46.     global newFile, newFilePointer  
  47.     newFile = "Replaced." + filename  
  48.     newFilePointer = codecs.open(newFile, "wb""utf-8")  
  49.       
  50.     fp = codecs.open(filename, "rb""utf-8")  
  51.     for line in fp:  
  52.         processLine(line)  
  53.     fp.close()  
  54.       
  55.     newFilePointer.close()  
  56.       
  57.     oldFile = "Old." + filename  
  58.     os.system("mv " + filename + " " + oldFile)  
  59.     os.system("mv " + newFile + " " + filename)  
  60.     #os.system("rm -f " + oldFile)   
  61.   
  62. if __name__ == "__main__":  
  63.     if len(sys.argv) > 1:  
  64.         output = os.popen("ls " + sys.argv[1]).read()  
  65.         filelist = re.split(" ", output)  
  66.         filelist = filelist[:-1]  
  67.         #print filelist   
  68.           
  69.         print "Localizing..."  
  70.           
  71.         for file in filelist:  
  72.             if os.path.exists(file):  
  73.                 try:  
  74.                     #print "Processing File :", file   
  75.                     processFile(file)  
  76.                 except Exception as e:  
  77.                     print e  
  78.           
  79.         print "Localization Done."  
之后需要做的事情参考:http://www.linuxidc.com/Linux/2012-03/55713.htm代码没用经过严格验证,请慎用。起码,没有检查该字符串是否已经加了NSLocalizedString宏。