Python 中文编码问题小结
2016-08-08 14:43
513 查看
1. 下面的语句要放在代码开头,指定文件编码, 可以识别 脚本中的所有字符和中文。
# -*- coding:utf-8 -*-
2. codecd 编码转换
如果想要读取文本中的中文,需要借助于codecs的一套open方法,而不是内置的open。#-*- coding:utf-8 -*- print '我是' import codecs f=codecs.open("e:/python/test_data/chinese.txt") content=f.read() f.close() if isinstance(content,unicode): print content.encode('utf-8') print "utf-8" else: print content.decode('gbk').encode('utf-8')
上面是为了显示内部编码的转换,简便用法如下:
chi1=codecs.open("e:/python/test_data/chinese.txt",'r','gbk') # 在打开时,指定文本的编码格式 content1=chi1.read() print content1 chi1.close()
3. codecs 编码小结:
gb2312/gbk 格式是中国标准的汉字编码格式,用于语言处理和编码转换。python的内部表示,是unicode编码。如果要做编码转换,需要:
decode encode
source ---------〉 unicode ----------〉 target
如果一个文件已经是unicode编码可以直接使用encode做编码转换。否则报错。例如:
s=u'中文'
此时可以先判断其编码方式是否是unicode:
isinstance(yourstr, unicode) #用来判断是否为unicode
相关文章推荐
- python2 中文编码问题小结
- python中文编码问题小结
- 通过读写文本文件小结“关于python处理中文编码的问题”
- python中文编码问题小结
- 通过读写文本文件小结“关于python处理中文编码的问题”
- Python中文编码问题
- Java中文&编码问题小结
- Python中文编码问题(转)
- python 中文编码问题
- python中文编码问题
- python的中文编码问题
- [原创]python中文编码老是出错问题。
- python中中文编码问题
- 利用python处理xml -- 中文编码问题
- Python中文编码问题
- Python中文编码问题
- python中的中文编码问题
- python 中文编码 问题
- 黄聪:python访问抓取网页常用命令(保存图片到本地、模拟POST、GET、中文编码问题)
- python中文编码问题