使用Python脚本处理OC中的中文字符串

22 篇文章 0 订阅

由于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://blog.csdn.net/jasonblog/article/details/7299544

代码没用经过严格验证,请慎用。起码,没有检查该字符串是否已经加了NSLocalizedString宏。


:)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值