Python2 中文编码处理
来源:互联网 发布:重庆八中数据谷中学 编辑:程序博客网 时间:2024/06/05 03:10
今天写了几个脚本,都遇到了中英文混编的情况。需求要将其中的中文标点符号切换为英文符号。
举个例子:
要将其中的中文半角逗号替换为英文逗号,为了方便后续的处理
如下处理:
UnicodeDecodeError: 'ascii' codec can't decode byte ...
python中字串分成两种,byte string 和unicode string
一般来说,设定好#coding=utf-8后,所有带中文的参数都会声明成utf-8编码的byte string
但是在函数中产生的字串则是unicode string
byte string 和 unicode string不能混用,所以就会抛出UnicodeDecodeError异常
所以有三种解决方案:
1. 全都转为byte string
2. 全都转为unicode string
3. 设置系统编码
1. 全都转为byte string
2. 全都转unicode.string
byte string 和unicode string相互转换
3. 设置系统默认编码
所以上面的问题就有解了:
调用setdefaultencoding设置系统encoding了
此外,还有读取UTF-8文件
可以使用codecs模块
在编写代码过程中,变量必须是ascii编码的,为了可以在文件中写中文,python需要知道文件不是ASCII编码
在
以上在python2中有效,在python3中已经区分了unicode string 和byte string,并且默认编码不再是ASCII
参考资料
http://www.evanjones.ca/python-utf8.html
举个例子:
tags = '你好,good, 国语'
要将其中的中文半角逗号替换为英文逗号,为了方便后续的处理
如下处理:
tags = tags.replace(',', ',')会抛出如下异常:
UnicodeDecodeError: 'ascii' codec can't decode byte ...
python中字串分成两种,byte string 和unicode string
一般来说,设定好#coding=utf-8后,所有带中文的参数都会声明成utf-8编码的byte string
但是在函数中产生的字串则是unicode string
byte string 和 unicode string不能混用,所以就会抛出UnicodeDecodeError异常
byte_str = 'hello, this is byte string'unicode_str = u'hello, this is unicode string'
所以有三种解决方案:
1. 全都转为byte string
2. 全都转为unicode string
3. 设置系统编码
1. 全都转为byte string
'你好' + request.forms.tags.encode('utf-8')
2. 全都转unicode.string
u'你好' + request.forms.tags
byte string 和unicode string相互转换
b_s = 'test'u_s = unicode(b_si, 'utf-8')back_to_b_s = u_s.encode('utf-8')
3. 设置系统默认编码
import sysreload(sys)sys.setdefaultencoding('utf-8')这样就可以任意的使用了
所以上面的问题就有解了:
tags = tags.replace(unicode(',','utf-8'), ',')或者
tags = tags.encode('utf-8').replace(',', ',')或者
调用setdefaultencoding设置系统encoding了
此外,还有读取UTF-8文件
可以使用codecs模块
import codecshandler = codecs.open('test', 'r', 'utf-8')u = handler.read() # returns a unicode string from the UTF-8 bytes in the filecodesc还能将传给write的unicode string转换为任何编码
在编写代码过程中,变量必须是ascii编码的,为了可以在文件中写中文,python需要知道文件不是ASCII编码
在
#!/usr/bin/env python下添加
# -*- coding: utf-8 -*-
以上在python2中有效,在python3中已经区分了unicode string 和byte string,并且默认编码不再是ASCII
参考资料
http://www.evanjones.ca/python-utf8.html
- Python2 中文编码处理
- python2 中文编码问题
- python2 中文编码问题
- Python2.7<中文编码>
- python2.7中文编码
- python2 中文编码问题小结
- python2处理中文字符问题
- 【编码】Python2.x的中文显示方法
- Python2获取中文文件名的编码问题
- python2.7中文编码报错问题
- Python2.x 中文md5编码问题
- Python2.7打印中文乱码处理
- JAVA中文编码处理
- 处理中文编码
- 编码中文汉字处理
- Jython中文编码处理
- Python2 编码
- Python2基础用法(中文编码,标识符,注释)
- #ifndef #define
- Zend Optimizer not Installed 出错的解决方法(大全)
- 加速度与加速计(UIAcceleration类,UIAccelerometer类及UIAccelerometerDelegate委托)
- 01-Debug模式
- android.view.InflateException异常处理
- Python2 中文编码处理
- main函数命令行参数
- PHP管理组件之间的依赖-Composer
- Java布局管理器(一)之布局管理器的工作过程及实现
- nyoj 187
- Java 回调
- The run destination iPhone 5.0 Simulator is not valid for running the scheme 'MyApp'
- vim
- ubuntu 10.04下编译linux内核make menuconfig报 'make menuconfig' requires the ncurses libraries 等错误