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


87

我已经使用电子邮件模块将此字符串从Quoted-printable解码为ISO-8859-1。这给了我像“ \ xC4pple”这样的字符串,它对应于“Äpple”(瑞典语中的Apple)。但是,我无法将这些字符串转换为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)

我该怎么办?

Answers:


121

尝试先解码,然后编码:

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

5
我在用我的语言(葡萄牙语)编码东西时遇到了一些问题,所以对我有用的是string.decode('iso-8859-1')。encode('latin1')。此外,在我的Python文件的顶部,我有这样的# - -编码:拉丁语1 - -
Moon13

148

这是一个普遍的问题,因此这里是一个相对详尽的说明。

对于非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在转换为另一种编码之前,必须先将a解码为unicode。

当然,所有这些变化在Python 3.x中都有。

希望是照亮的。

进一步阅读

还有阿明·罗纳彻(Armin Ronacher)的极具说明性的咆哮:


12
感谢您抽出
宝贵

5
哇。简洁,非常容易理解,并通过示例进行说明。感谢您使Intertubes变得更好。
Monkey Boson

22

对于Python 3:

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

我将其用于错误编码为iso-8859-1(显示类似VeÅ\x99ejné的单词)而不是utf-8的文本。此代码产生正确的版本Veřejné


哪里bytes来的?
alvas

1
说明文件:位元组。另请参阅此问题及其答案。
Michal Skop 2015年

3
对于通过请求下载的文件,其标题缺失或不正确:r = requests.get(url)然后直接设置r.encoding = 'utf-8'对我
有用

bytes.decode方法文档。
mike

10

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

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

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.