Skip to content

Instantly share code, notes, and snippets.

@siqin
Created March 3, 2012 10:17
Show Gist options
  • Save siqin/1965385 to your computer and use it in GitHub Desktop.
Save siqin/1965385 to your computer and use it in GitHub Desktop.
Localization The Objective-C Code
#!/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.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment