【发布时间】:2012-01-25 21:33:43
【问题描述】:
给定一个编码为整数的字符代码,如何将字符代码(例如 utf-8)再作为整数获取?
【问题讨论】:
标签: python unicode encoding utf-8 character-codes
给定一个编码为整数的字符代码,如何将字符代码(例如 utf-8)再作为整数获取?
【问题讨论】:
标签: python unicode encoding utf-8 character-codes
UTF-8 is a variable-length encoding,所以我假设您的意思是“Unicode 代码点”。使用chr()将字符码转换为字符,解码,使用ord()获取码位。
>>> ord(chr(145).decode('koi8-r'))
9618
【讨论】:
chr() arg not in range(256) for 'shift_jisx0213'
chr 仅支持 ASCII,因此仅支持 [0..255] 范围内的数字。使用 unichr 代替 Unicode 支持。
UnicodeEncodeError: 'ascii' codec can't encode character u'\u8140' in position 0 : ordinal not in range(128)
chr(145) 可能等同于 Python 2 上的 unichr(145).encode('latin1'),如果输入在 range(256) 中。 Python 3 上没有unichr,它被重命名为chr。如果需要,通常可以修复输入:reinterpreted = unistr.encode(one_encoding).decode(another_encoding)
如果它们都是单字节编码,则只能将“整数”从一种编码映射到另一种编码。
这是一个使用“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(对于0 到127 范围内的代码)或unichr(对于0 到sys.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 范围内的代码(但只是微不足道,因为代码将始终相同)。
【讨论】:
以下是编码/解码舞蹈如何工作的示例:
>>> 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
٤
【讨论】: