Python如何获取不同编码下的字符编码?

18

给定一个整数编码的字符代码,在另一种编码中如何获取utf-8的字符代码,并再次作为整数呈现?

3个回答

16

UTF-8是一种可变长度编码,因此我假设您实际上想说的是 "Unicode代码点"。使用chr()将字符编码转换为字符,解码它,并使用ord()获取代码点。

>>> ord(chr(145).decode('koi8-r'))
9618

chr()的参数不在范围内(256)'shift_jisx0213' - user975135
5
在Python 2中,chr仅支持ASCII编码,因此仅适用于在[0..255]范围内的数字。如需支持Unicode,请使用unichr代替。 - poke
嗯,UnicodeEncodeError: 'ascii' codec can't encode character u'\u8140' in position 0: ordinal not in range(128) - user975135
如果输入在range(256)范围内,那么在Python 2中chr(145)可能等同于unichr(145).encode('latin1')。在Python 3中没有unichr,它被重命名为chr。如果需要修复输入,则通常使用以下方法:reinterpreted = unistr.encode(one_encoding).decode(another_encoding) - jfs

12

只有当两种编码都是单字节编码时,才能将“整数”从一种编码映射到另一种编码。

以下是使用“iso-8859-15”和“cp1252”(也称为“ANSI”)的示例:

>>> s = u'€'
>>> s.encode('iso-8859-15')
'\xa4'
>>> s.encode('cp1252')
'\x80'
>>> ord(s.encode('cp1252'))
128
>>> ord(s.encode('iso-8859-15'))
164

请注意,此处使用ord是为了获取编码字节的序号。在原始Unicode字符串上使用ord会得到其Unicode代码点

>>> ord(s)
8364

ord函数的反向操作可以使用chr(对于代码在0127范围内)或unichr(对于代码在0sys.maxunicode范围内)来完成:

>>> print chr(65)
A
>>> print unichr(8364)
€

对于多字节编码来说,通常不可能进行简单的“整数映射”。

以下是与上面相同的示例,但使用的是“iso-8859-15”和“utf-8”:

>>> s = u'€'
>>> s.encode('iso-8859-15')
'\xa4'
>>> s.encode('utf-8')
'\xe2\x82\xac'
>>> [ord(c) for c in s.encode('iso-8859-15')]
[164]
>>> [ord(c) for c in s.encode('utf-8')]
[226, 130, 172]

"utf-8"编码使用三个字节来编码相同的字符,因此无法进行一对一的映射。尽管如此,许多编码(包括 "utf-8")都被设计为与ASCII兼容,因此通常可以对0-127范围内的代码进行映射(但只是非常简单的映射,因为代码始终相同)。


2
这是一个编码/解码操作的示例:
>>> s = b'd\x06'             # perhaps start with bytes encoded in utf-16
>>> map(ord, s)              # show those bytes as integers
[100, 6]
>>> u = s.decode('utf-16')   # turn the bytes into unicode
>>> print u                  # show what the character looks like
٤
>>> print ord(u)             # show the unicode code point as an integer
1636
>>> t = u.encode('utf-8')    # turn the unicode into bytes with a different encoding
>>> map(ord, t)              # show that encoding as integers
[217, 164]

希望这有所帮助 :-)
如果您需要直接从整数构造 Unicode,请使用unichr
>>> u = unichr(1636)
>>> print u
٤

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接