您的位置:首页 > 编程语言 > Python开发

Python处理中文语言——读取中文

2016-09-05 14:59 253 查看
本文解决问题:

1、导入中文txt文本,并转换为unicode

2、导入包含中文的py file

-----------------------------------解决问题一:导入中文txt文本,并转换为unicode-----------------------------------

基础概念:

1、unicode、UTF-8

简单理解,unicode是一种处理所有非英文语言的编码方式,即将每个语言中的每个文字设置成不同的数字,避免造成混乱。unicode目前覆盖了世界上的主流语言,有超过一百多万个编号。UTF-8是实现unicode的一种方式。ASCII是不同于unicode的另外一种编码方式。详细介绍可见参考文章1。

2、encoding

将文本转化为数字的一系列规则叫作encoding。

核心代码

string.decode(*encoding*)   # from <type 'str'> to <type 'unicode'>
unicode.encode(*encoding*)   # from <type 'unicode'> to <type 'str'>


执行步骤:

1、将原始文本的编码方式保存为utf-8格式。

2、在python程序中导入文本

fr = open('all.txt','r')   #读写模式:r-只读;r+读写;w-新建(会覆盖原有文件);更多信息见参考文章2
all_utf8 = fr.read()
all_utf8   #屏幕上会出现类似“\xe86\xe95\xa3”的文字</span>
3、将原始文本的编码方式解码,即转换为unicode。可使用下面两种方式的任意一种。

all_uni = all_utf8.decode("utf-8")


all_uni = unicode(all_utf8, 'utf-8')

4、比较转换前和转换后的文本

print all_utf8   #乱码
print all_uni   #中文


处理非英文文本,最重要的点是:

1、Decode early (尽早decode, 将文件中的内容转化成 unicode 再进行下一步处理)

def to_unicode_or_bust(obj, encoding='utf-8'):
if isinstance(obj, basestring):   #检查是否为字符串
if not isinstance(obj, unicode):   #检查编码是否为unicode
obj = unicode(obj, encoding)   #使用UTF-8,将文本转换为unicode
return obj
'''检查一个obejct是否是字符串,如是非unicode的字符串将其转换成unicode。'''


2、Unicode everywhere (程序内部处理都用unicode)

to_unicode_or_bust(all_utf8)


3、Encode late (最后encode回所需的encoding, 例如把最终结果写进结果文件)

file = open('all_out.txt','wb')   #创建一个all_out的txt文件
file.write(all_uni.encode('utf-8'))   #用utf-8编码方式保存all_uni
file.close()   #保存完毕


其它:

1、查看python默认的编码方式

import sys
sys.getdefaultencoding()   # 'ascii'

2、更改python默认的编码方式

sys.setdefaultencoding('utf-8')


3、使用codecs模块导入文档:用codecs提供的open方法,可以指定打开的文件的语言编码,并在读取的时候自动转换为unicode。

import codecs
file = open('all_out.txt', 'r', encoding = 'utf-8')


4、BOM

windows下加载文本,有时会出现BOM头,即在文件的开头有'特殊'的记号标识该文件属于UTF-8编码。

使用codecs模块,检查是否有BOM头的方法

fr = open('all.txt','r')
sample = fr.read(4)
sample.startswith(codecs.BOM_UTF16_LE) or sample.startswith(codecs.BOM_UTF16_BE)


UTF-16格式的文本在decode是会自动删除BOM;UTF-8文本删除BOM使用如下代码

string.decode('utf-8-sig')


--------------------------------------------解决问题二:导入包含中文的py
file--------------------------------------------

Python默认使用ASCII编码作为标准编码方式,所以需要在文档的第一行或第二行注明我们的编码方式。

核心代码(标注方式)

# coding=<encoding name>
或者

#!/usr/bin/python
# -*- coding: <encoding name> -*-
或者

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
这里只要符合正则表达式"^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)"即可,所以等号也可以替换为冒号

执行步骤

1、在记事本中输入以下代码,使用ANSI格式保存,命名为test.py

# coding=UTF-8
s = "中文"
print s
2、在python中导入py file

import test

其它:

我们也可以使用普通文本来表示编码,例如在记事本中输入:

# This Python file uses the following encoding: utf-8
s = "中文"
print s


参考文章:

1、字符编码笔记:ASCII,Unicode和UTF-8
http://www.ruanyifeng.com/blog/2007/10/ascii_unicode_and_utf-8.html
2、python:open/文件操作
http://www.cnblogs.com/dkblog/archive/2011/02/24/1980651.html
3、Python处理中文的时候的一些小技巧
http://coolshell.cn/articles/461.html
4、PEP 263 -- Defining Python Source Code Encodings
https://www.python.org/dev/peps/pep-0263/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python BOM