Python: 从ISO-8859-1/latin1转换为UTF-8

104 投票
5 回答
291589 浏览
提问于 2025-04-16 20:37

我有一个字符串,它是通过电子邮件模块从Quoted-printable格式解码成ISO-8859-1格式的。这样我得到了像"\xC4pple"这样的字符串,它对应的意思是"Äpple"(瑞典语中的苹果)。

但是,我不知道怎么把这些字符串转换成UTF-8格式。

>>> apple = "\xC4pple"
>>> apple
'\xc4pple'
>>> apple.encode("UTF-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in     range(128)

我该怎么办呢?

5 个回答

26

对于Python 3:

bytes(apple,'iso-8859-1').decode('utf-8')

我用这个方法来处理一个错误编码为iso-8859-1的文本(显示的单词像是VeÅ\x99ejné),而不是utf-8。这个代码能正确输出Veřejné

177

这是一个常见的问题,下面我会详细说明一下。

对于非Unicode字符串(也就是那些没有 u 前缀的字符串,比如 u'\xc4pple'),我们需要先把它从本地编码(通常是 iso8859-1latin1,除非用了一些神秘的 sys.setdefaultencoding 函数进行修改)解码成 unicode,然后再编码成可以显示你想要的字符的字符集。在这种情况下,我推荐使用 UTF-8

首先,这里有一个实用的工具函数,可以帮助你理解 Python 2.7 中字符串和 Unicode 的关系:

>>> def tell_me_about(s): return (type(s), s)

普通字符串

>>> v = "\xC4pple" # iso-8859-1 aka latin1 encoded string

>>> tell_me_about(v)
(<type 'str'>, '\xc4pple')

>>> v
'\xc4pple'        # representation in memory

>>> print v
?pple             # map the iso-8859-1 in-memory to iso-8859-1 chars
                  # note that '\xc4' has no representation in iso-8859-1, 
                  # so is printed as "?".

解码一个 iso8859-1 字符串 - 将普通字符串转换为 Unicode

>>> uv = v.decode("iso-8859-1")
>>> uv
u'\xc4pple'       # decoding iso-8859-1 becomes unicode, in memory

>>> tell_me_about(uv)
(<type 'unicode'>, u'\xc4pple')

>>> print v.decode("iso-8859-1")
Äpple             # convert unicode to the default character set
                  # (utf-8, based on sys.stdout.encoding)

>>> v.decode('iso-8859-1') == u'\xc4pple'
True              # one could have just used a unicode representation 
                  # from the start

更详细的说明 - 以“Ä”为例

>>> u"Ä" == u"\xc4"
True              # the native unicode char and escaped versions are the same

>>> "Ä" == u"\xc4"  
False             # the native unicode char is '\xc3\x84' in latin1

>>> "Ä".decode('utf8') == u"\xc4"
True              # one can decode the string to get unicode

>>> "Ä" == "\xc4"
False             # the native character and the escaped string are
                  # of course not equal ('\xc3\x84' != '\xc4').

编码为 UTF

>>> u8 = v.decode("iso-8859-1").encode("utf-8")
>>> u8
'\xc3\x84pple'    # convert iso-8859-1 to unicode to utf-8

>>> tell_me_about(u8)
(<type 'str'>, '\xc3\x84pple')

>>> u16 = v.decode('iso-8859-1').encode('utf-16')
>>> tell_me_about(u16)
(<type 'str'>, '\xff\xfe\xc4\x00p\x00p\x00l\x00e\x00')

>>> tell_me_about(u8.decode('utf8'))
(<type 'unicode'>, u'\xc4pple')

>>> tell_me_about(u16.decode('utf16'))
(<type 'unicode'>, u'\xc4pple')

Unicode、UTF 和 latin1 之间的关系

>>> print u8
Äpple             # printing utf-8 - because of the encoding we now know
                  # how to print the characters

>>> print u8.decode('utf-8') # printing unicode
Äpple

>>> print u16     # printing 'bytes' of u16
���pple

>>> print u16.decode('utf16')
Äpple             # printing unicode

>>> v == u8
False             # v is a iso8859-1 string; u8 is a utf-8 string

>>> v.decode('iso8859-1') == u8
False             # v.decode(...) returns unicode

>>> u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16')
True              # all decode to the same unicode memory representation
                  # (latin1 is iso-8859-1)

Unicode 异常

 >>> u8.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
  ordinal not in range(128)

>>> u16.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
  ordinal not in range(128)

>>> v.encode('iso8859-1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
  ordinal not in range(128)

我们可以通过将特定编码(如 latin-1、utf8、utf16)转换为 Unicode 来解决这些问题,例如 u8.decode('utf8').encode('latin1')

因此,我们可以总结出以下原则和概念:

  • str 类型是一组字节,可能有多种编码方式,比如 Latin-1、UTF-8 和 UTF-16。
  • unicode 类型是一组字节,可以转换为多种编码,最常见的是 UTF-8 和 latin-1(iso8859-1)。
  • print 命令有 自己的一套编码逻辑,它的设置是 sys.stdout.encoding,默认是 UTF-8。
  • 在转换为其他编码之前,必须先将 str 解码为 Unicode。

当然,这些在 Python 3.x 中都有所不同。

希望这些信息对你有帮助。

进一步阅读

还有 Armin Ronacher 的一些非常生动的讨论:

136

先试着解码,然后再编码:

apple.decode('iso-8859-1').encode('utf8')

撰写回答