如何使用Python将带有cp1252字符的unicode字符串转换成UTF8?

2024-10-01 13:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在通过一个API获取文本,该API返回带有windows编码的撇号(\x92)的字符:

> python
>>> title = u'There\x92s thirty days in June'
>>> title
u'There\x92s thirty days in June'
>>> print title
Theres thirty days in June
>>> type(title)
<type 'unicode'>

我试图将这个字符串转换成UTF-8,这样它就会返回:“六月有三十天”

当我试图解码或编码这个unicode字符串时,它会抛出一个错误:

^{pr2}$

如果我将字符串初始化为纯文本,然后对其进行解码,则可以:

>>>title = 'There\x92s thirty days in June'
>>> type(title)
<type 'str'>
>>>print title.decode('cp1252')
There’s thirty days in June

我的问题是如何将得到的unicode字符串转换成纯文本字符串以便解码?在


Tags: 字符串in文本api编码titletypeunicode
1条回答
网友
1楼 · 发布于 2024-10-01 13:31:12

似乎您的字符串是用latin1(因为它是unicode类型)解码的

  1. 要将其转换回原来的字节,需要使用该编码(latin1)对其进行编码
  2. 然后为了得到文本(unicode),你必须使用正确的编解码器(cp1252)解码
  3. 最后,如果你想得到utf-8字节,你必须使用UTF-8编解码器对进行编码。在

代码:

>>> title = u'There\x92s thirty days in June'
>>> title.encode('latin1')
'There\x92s thirty days in June'
>>> title.encode('latin1').decode('cp1252')
u'There\u2019s thirty days in June'
>>> print(title.encode('latin1').decode('cp1252'))
There’s thirty days in June
>>> title.encode('latin1').decode('cp1252').encode('UTF-8')
'There\xe2\x80\x99s thirty days in June'
>>> print(title.encode('latin1').decode('cp1252').encode('UTF-8'))
There’s thirty days in June

取决于API是接受文本(unicode)还是bytes,3。可能没有必要。在

相关问题 更多 >