歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Python腳本處理OC中的中文字符串

使用Python腳本處理OC中的中文字符串

日期:2017/3/1 10:27:32   编辑:Linux編程

由於Xcode對中文支持良好,所以在開發過程中經常直接使用中文字符串。

不過蘋果推薦多語言化,需要為中文字符串添加個NSLocalizedString宏。

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. '''''
  4. Localization The Objective-C Code
  5. @"..." --> NSLocalizedString(@"...", nil)
  6. Jason Lee 2012-03-01
  7. '''
  8. import os, sys
  9. import re
  10. import codecs
  11. targetPattern = re.compile('@"[^"]+"')
  12. global newFile, newFilePointer
  13. def isChineseCharacter(ch):
  14. return 0x4e00 <= ord(ch) <= 0x9fa5
  15. def hasChineseCharacter(str):
  16. for char in str:
  17. if isChineseCharacter(char):
  18. return True
  19. return False
  20. def buildNewString(oldStr):
  21. newStrPrefix = 'NSLocalizedString('
  22. newStrSuffix = ', nil)'
  23. newStr = newStrPrefix + oldStr + newStrSuffix
  24. return newStr
  25. def processLine(line):
  26. global newFile, newFilePointer
  27. matchResult = targetPattern.findall(line)
  28. for result in matchResult:
  29. if hasChineseCharacter(result):
  30. #print result, buildNewString(result)
  31. p = re.compile(result)
  32. line = p.sub(buildNewString(result), line)
  33. newFilePointer.write(line)
  34. def processFile(filename):
  35. #Xcode file is saved with utf-8
  36. global newFile, newFilePointer
  37. newFile = 'Replaced.' + filename
  38. newFilePointer = codecs.open(newFile, 'wb', 'utf-8')
  39. fp = codecs.open(filename, 'rb', 'utf-8')
  40. for line in fp:
  41. processLine(line)
  42. fp.close()
  43. newFilePointer.close()
  44. oldFile = 'Old.' + filename
  45. os.system('mv ' + filename + ' ' + oldFile)
  46. os.system('mv ' + newFile + ' ' + filename)
  47. #os.system('rm -f ' + oldFile)
  48. if __name__ == "__main__":
  49. if len(sys.argv) > 1:
  50. output = os.popen('ls ' + sys.argv[1]).read()
  51. filelist = re.split('\n', output)
  52. filelist = filelist[:-1]
  53. #print filelist
  54. print 'Localizing...'
  55. for file in filelist:
  56. if os.path.exists(file):
  57. try:
  58. #print 'Processing File :', file
  59. processFile(file)
  60. except Exception as e:
  61. print e
  62. print 'Localization Done.'

之後需要做的事情參考:http://www.linuxidc.com/Linux/2012-03/55713.htm

代碼沒用經過嚴格驗證,請慎用。起碼,沒有檢查該字符串是否已經加了NSLocalizedString宏。

Copyright © Linux教程網 All Rights Reserved