python对配置文件对中文转换Unicode编码
最近需要对Pentaho国际化,其中需要配置properties文件,要将里面的中文用Unicode十六进制表示,以下是python实现代码。只对等号后面的字符做转换。文件名从命令行传入。
1 #!/usr/bin/python
2 # -*- coding:utf-8 -*-
3 import re,os
4 import sys
5 reload(sys)
6
7 def decode(filename):
8 # print filename
9 try:
10 f = open(filename, 'r')
11 except:
12 print "File %s open error! No such file!" % filename
13 return
14 while 1:
15 line = f.readline().replace("\n","")
16 if not line:
17 break
18 p = re.compile(r'=')
19 str = p.split(line)
20 if len(str) == 2:
21 str2 = repr(str[1].decode('utf-8')).replace('u\'',"").replace('\'',"")
22 print "%s%s%s" % (str[0],"=",str2)
23 else:
24 print line
25
26 if __name__ == '__main__':
27 print sys.argv
28 decode(os.path.join(os.path.dirname(__file__), sys.argv[1]))