Differences between revisions 2 and 3
Revision 2 as of 2008-08-21 14:02:28
Size: 3223
Editor: ZoomQuiet
Comment:
Revision 3 as of 2008-08-21 14:05:08
Size: 3226
Editor: ZoomQuiet
Comment:
Deletions are marked like this. Additions are marked like this.
Line 21: Line 21:
**常见的编码转换分为以下几种情况:** '''常见的编码转换分为以下几种情况:'''
Line 34: Line 34:
=== 聲明成 unicode 后进行 === 
=== 聲明成 unicode 后进行 ===

TableOfContents

Include(ZPyUGnav)

Python 编码转换

{{{k <yanbo.yuan@gmail.com> reply-to python-cn@googlegroups.com, to python-cn@googlegroups.com, date Sat, Mar 29, 2008 at 10:09 AM subject [CPyUG:45138] python 编码转换[zt] }}} 主要介绍了python的编码机制,unicode, utf-8, utf-16, GBK, GB2312,ISO-8859-1 等编码之间的转换。

常见的编码转换分为以下几种情况:

unicode 缺失转换

Tim Wang <tianyao.wang@gmail.com>
reply-to        python-cn@googlegroups.com
to      python-cn@googlegroups.com
date    Thu, Aug 21, 2008 at 21:02
subject [CPyUG:63028] 有问题请教

S="\u5317\u4eac"

  • 如何把它转换成gb18030的北京?
  • S.decode('utf8').encode('gb18030')好像不行。

聲明成 unicode 后进行

Jimmy Kuu <jimmy.kuu@gmail.com>
reply-to        python-cn@googlegroups.com
to      python-cn@googlegroups.com
date    Thu, Aug 21, 2008 at 21:18

Toggle line numbers
   1 s = "\u5317\u4eac"
   2 s = eval("u'%s'" % s)
   3 s.encode('gb18030')

unicode 转换为其它编码(GBK, GB2312等)

例如:a为unicode编码 要转为gb2312。a.encode('gb2312')

Toggle line numbers
   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312

其它编码(utf-8,GBK)转换为unicode

例如:a为gb2312编码,要转为unicode. unicode(a, 'gb2312')或a.decode('gb2312')

Toggle line numbers
   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312
   5 
   6 a_unicode = a_gb2312.decode('gb2312')
   7 assert(a_unicode == a)
   8 a_utf_8 = a_unicode.encode('utf-8')
   9 print a_utf_8

非unicode编码之间的转换

编码1(GBK,GB2312) 转换为 编码2(utf-8,utf-16,ISO-8859-1)

可以先转为unicode再转为编码2

如gb2312转utf-8

Toggle line numbers
   1 # -*- coding=gb2312 -*-
   2 a = u"中文"
   3 a_gb2312 = a.encode('gb2312')
   4 print a_gb2312
   5 
   6 a_unicode = a_gb2312.decode('gb2312')
   7 assert(a_unicode == a)
   8 a_utf_8 = a_unicode.encode('utf-8')
   9 print a_utf_8

判断字符串的编码

isinstance(s, str) 用来判断是否为一般字符串 isinstance(s, unicode) 用来判断是否为unicode 如果一个字符串已经是unicode了,再执行unicode转换有时会出错(并不都出错)

下面代码为将任意字符串转换为unicode

Toggle line numbers
   1 def u(s, encoding):
   2    if isinstance(s, unicode):
   3        return s
   4    else:
   5        return unicode(s, encoding)

unicode 与其它编码之间的区别

  • 为什么不所有的文件都使用unicode,还要用GBK,utf-8等编码呢?
    • unicode可以称为抽象编码,也就是它只是一种内部表示,一般不能直接保存。

保存到磁盘上时,需要把它转换为对应的编码,如utf-8和utf-16。

其它方法

除上以上的编码方法,在读写文件时还可以使用codecs的open方法在读写时进行转换。


反馈

创建 by -- ZoomQuiet [DateTime(2008-03-29T03:22:30Z)]

PageComment2

[:/PageCommentData:PageCommentData]

PyEnCode (last edited 2010-03-10 03:36:31 by ZoomQuiet)