python处理中文
2016-01-18 09:36
567 查看
来源:http://www.djangochina.cn/forum.php?mod=viewthread&tid=118977&extra=page%3D1
python, 中文
字符串在Python内部的表示是unicode编码,因此,在做编码转换时,通常需要以unicode作为中间编码,即先将其他编码的字符串解码(decode)成unicode,再从unicode编码(encode)成另一种编码。 decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode('gb2312'),表示将gb2312编码的字符串str1转换成unicode编码。 encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode('gb2312'),表示将unicode编码的字符串str2转换成gb2312编码。 代码中字符串的默认编码与代码文件本身的编码一致。 如:s='中文' 如果是在utf8的文件中,该字符串就是utf8编码,如果是在gb2312的文件中,则其编码为gb2312。这种情况下,要进行编码转换,都需要先用decode方法将其转换成unicode编码,再使用encode方法将其转换成其他编码。 如果字符串是这样定义:s=u'中文' 则该字符串的编码就被指定为unicode了,即python的内部编码,而与代码文件本身的编码无关。因此,对于这种情况做编码转换,只需要直接使用encode方法将其转换成指定编码即可。 以日期为例: #raw_date is a gbk-coding string def parse_date(raw_date): entry_date = raw_date.decode("gbk") month = int(entry_date[0]) #unicode 对中文的长度是1,如果6月2日那么长度就是4,如果6月25日,长度就是5 if len(entry_date) == 5: day = 10 * int(entry_date[2]) + int(entry_date[3]) else: day = int(entry_date[2]) return 2013, month, day 复制代码 |
相关文章推荐
- python no module named yaml
- python小白-day3 深浅拷贝
- python进程池:multiprocessing.pool
- python学习----------面向对象2
- 【Python数据分析】工作日发文章比周末发文章访问量高?
- 30. Substring with Concatenation of All Words leetcode Python 2016 new season
- python抓取京东商品颜色&beautifulsoup的一些常用函数
- python的threading和multiprocessing模块初探
- 由 python 自定义 class 引发的两个问题
- 在Python3.4下,用cx_freeze打包PyQt4程序
- python 堡垒机
- python MySQLdb
- python 堡垒机续-----终端方式
- python小白学习之路啊
- python做自动化测试,对java代码做单元测试(2)
- Python扫描指定目录下(包括子目录)的文件
- 用python做自动化测试--对Java代码做单元测试 (1)
- 编写python脚本-->批量下载淘宝 2012年ADC技术嘉年华PDF文件
- 2016/01/18 Python学习1
- python爬虫模拟登录之验证码