|
| 1 | +# 规范 |
| 2 | +- 脚本文件编码 |
| 3 | +由于需要经常性使用到中文字符,因此Python脚本新建后,请在头部添加代码: |
| 4 | +``` |
| 5 | +# coding: utf-8 |
| 6 | +``` |
| 7 | +或者为pycharm设置代码模版,这样每次新建Python文件时会自动带上以上代码。如果不添加,即使中文字符串以u开头,也是编译不通过的。 |
| 8 | + |
| 9 | +# UNICODE |
| 10 | +- 脚本中的字符最好使用UNICODE编码(英文可以不需要,但是中文尽量使用),因为UNICODE编码是比较好的“中间”字符集,比较容易向GBK和UTF-8转换。例如: |
| 11 | +``` |
| 12 | +print u"你好" |
| 13 | +``` |
| 14 | +如果不带u的字符在包含了# coding: utf-8的脚本中默认字符为UTF-8,一般也不会有什么问题。 |
| 15 | + |
| 16 | + |
| 17 | +- UNICODE转GBK: |
| 18 | +``` |
| 19 | +# 带u的字符串为unicode |
| 20 | +s.encode('gbk') |
| 21 | +``` |
| 22 | + |
| 23 | +- UNICODE转UTF-8 |
| 24 | +``` |
| 25 | +# 带u的字符串为unicode |
| 26 | +s.encode('utf-8') |
| 27 | +``` |
| 28 | + |
| 29 | +# GBK |
| 30 | +- GBK转UNICODE |
| 31 | + |
| 32 | +Windows下的命令行参数为GBK编码,因此需要对字符串进行转换,转换方法有两种。 |
| 33 | + |
| 34 | +方法一: |
| 35 | + |
| 36 | +``` |
| 37 | +
|
| 38 | +# Create a new Unicode object from the given encoded string. |
| 39 | +# encoding defaults to the current default string encoding. |
| 40 | +# errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'. |
| 41 | +
|
| 42 | +unicode(s, "gbk", "ignore") |
| 43 | +``` |
| 44 | +方法二: |
| 45 | +``` |
| 46 | +s.decode('gbk', 'ignore') |
| 47 | +``` |
| 48 | + |
| 49 | +跨平台判断: |
| 50 | + |
| 51 | +``` |
| 52 | +if sys.platform == 'win32': |
| 53 | + # win下命令行参数为gbk编码,转换字符 |
| 54 | + pass |
| 55 | +else: |
| 56 | + pass |
| 57 | +``` |
| 58 | + |
| 59 | +# UTF-8 |
| 60 | +- UTF-8转换为UNICODE |
| 61 | +``` |
| 62 | +unicode(s, "utf-8", "ignore") |
| 63 | +``` |
| 64 | +或: |
| 65 | +``` |
| 66 | +s.decode('utf-8', 'ignore') |
| 67 | +``` |
| 68 | + |
| 69 | + |
| 70 | +# 汇总整理成函数库 |
| 71 | + |
| 72 | +``` |
| 73 | +# win下命令行参数为gbk编码:star.gbk2unicode(sys.argv[1]) + u'也有' |
| 74 | +def gbk2unicode(s): |
| 75 | + return s.decode('gbk', 'ignore') |
| 76 | +
|
| 77 | +# 脚本文件#coding:utf-8时默认不带u的字符串为utf8字符串:star.utf82unicode('我') |
| 78 | +def utf82unicode(s): |
| 79 | + return s.decode('utf-8', 'ignore') |
| 80 | +
|
| 81 | +# 带u的字符串为unicode |
| 82 | +# star.unicode2gbk(u'\u4e5f\u6709') |
| 83 | +# star.unicode2gbk(u'也有') |
| 84 | +def unicode2gbk(s): |
| 85 | + return s.encode('gbk') |
| 86 | +
|
| 87 | +# 带u的字符串为unicode |
| 88 | +# star.unicode2utf8(u'\u4e5f\u6709') |
| 89 | +# star.unicode2utf8(u'也有') |
| 90 | +def unicode2utf8(s): |
| 91 | + return s.encode('utf-8') |
| 92 | +
|
| 93 | +# win下命令行参数为gbk编码:star.gbk2utf8(sys.argv[1]) + '也有' |
| 94 | +def gbk2utf8(s): |
| 95 | + return s.decode('gbk', 'ignore').encode('utf-8') |
| 96 | +
|
| 97 | +def utf82gbk(s): |
| 98 | + return s.decode('utf-8', 'ignore').encode('gbk') |
| 99 | +
|
| 100 | +``` |
0 commit comments