由於Xcode對中文支持良好,所以在開發過程中經常直接使用中文字符串。
不過蘋果推薦多語言化,需要為中文字符串添加個NSLocalizedString宏。
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
-
- '''''
- Localization The Objective-C Code
- @"..." --> NSLocalizedString(@"...", nil)
- Jason Lee 2012-03-01
- '''
-
- import os, sys
- import re
- import codecs
-
- targetPattern = re.compile('@"[^"]+"')
- global newFile, newFilePointer
-
- def isChineseCharacter(ch):
- return 0x4e00 <= ord(ch) <= 0x9fa5
-
- def hasChineseCharacter(str):
- for char in str:
- if isChineseCharacter(char):
- return True
- return False
-
- def buildNewString(oldStr):
- newStrPrefix = 'NSLocalizedString('
- newStrSuffix = ', nil)'
- newStr = newStrPrefix + oldStr + newStrSuffix
- return newStr
-
- def processLine(line):
- global newFile, newFilePointer
-
- matchResult = 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-8
- global newFile, newFilePointer
- newFile = 'Replaced.' + filename
- newFilePointer = 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.' + filename
- os.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[1]).read()
- filelist = re.split('\n', output)
- filelist = filelist[:-1]
- #print filelist
-
- print 'Localizing...'
-
- for file in filelist:
- if os.path.exists(file):
- try:
- #print 'Processing File :', file
- processFile(file)
- except Exception as e:
- print e
-
- print 'Localization Done.'
之後需要做的事情參考:http://www.linuxidc.com/Linux/2012-03/55713.htm
代碼沒用經過嚴格驗證,請慎用。起碼,沒有檢查該字符串是否已經加了NSLocalizedString宏。