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

104

我有一个字符串,它已经使用电子邮件模块从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个回答

175

这是一个常见的问题,因此这里有一个相对详细的说明。

对于非Unicode字符串(即没有u前缀的字符串,例如u'\xc4pple'),必须从本地编码(iso8859-1/latin1,除非 使用神秘的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的非常生动的抨击:


17
感谢你抽出时间提供如此详细的解释,这是我在stackoverflow上找到的最好的答案之一 :) - ruyadorno
6
哇,非常简明扼要,易于理解,并通过示例进行了解释。感谢您让互联网变得更好。 - Monkey Boson

135

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

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

6
我在将某些内容编码为我的语言 (葡萄牙语) 时遇到了一些问题,所以对我有用的是 string.decode('iso-8859-1').encode('latin1')。此外,在我的 Python 文件顶部,我有这个 # -- coding: latin-1 --。 - Moon13
4
string.decode('iso-8859-1').encode('latin1')string完全等价。('latin-1''iso-8859-1'的别名。) - tripleee

26

对于 Python 3:

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

我使用了这段代码来处理一个以错误编码 iso-8859-1 显示的文本(显示为诸如 VeÅ\x99ejné 的单词),而不是 utf-8。这段代码能够生成正确的版本:Veřejné


1
bytes 是从哪里来的? - alvas
1
文档:bytes。 还可以参考这个问题及其答案。 - Michal Skop
3
对于使用Requests下载的文件,如果出现缺失或不正确的头部信息:r = requests.get(url) 并直接设置 r.encoding = 'utf-8' 对我有效。 - Michal Skop
1
bytes.decode 方法文档。 - mike
成功了!爱你! - MrTo-Kane

12

解码为Unicode,将结果编码为UTF8。

apple.decode('latin1').encode('utf8')

AttributeError: 'str' object has no attribute 'decode' - undefined

0
concept = concept.encode('ascii', 'ignore') 
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())

我这样做,不确定是否是一个好的方法,但它每次都有效!!


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