如何将字符串从CP-1251转换为UTF-8?

jsn*_*ack 23 python wxpython utf-8 cp1251

我正在使用mutagen将ID3标签数据从CP-1251/CP-1252转换为UTF-8.在Linux中没有问题.但在Windows上,调用SetValue()wx.TextCtrl会产生错误:

UnicodeDecodeError:'ascii'编解码器无法解码位置0中的字节0xc3:序数不在范围内(128)

我从mutagen中提取的原始字符串(假设为CP-1251编码)是:

u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
Run Code Online (Sandbox Code Playgroud)

我尝试将其转换为UTF-8:

dd = d.decode('utf-8')
Run Code Online (Sandbox Code Playgroud)

...甚至将默认编码从ASCII更改为UTF-8:

sys.setdefaultencoding('utf-8')
Run Code Online (Sandbox Code Playgroud)

......但是我得到了同样的错误.

Joh*_*rra 25

如果您确定输入中有cp1251,则可以这样做

d.decode('cp1251').encode('utf8')
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 5

您的字符串d是Unicode字符串,而不是 UTF-8编码的字符串!所以你不能decode(),你必须encode()使用UTF-8或你需要的任何编码.

>>> d = u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
>>> d
u'\xc1\xe5\xeb\xe0\xff \xff\xe1\xeb\xfb\xed\xff \xe3\xf0\xee\xec\xf3'
>>> print d
Áåëàÿ ÿáëûíÿ ãðîìó
>>> a.encode("utf-8")
'\xc3\x81\xc3\xa5\xc3\xab\xc3\xa0\xc3\xbf \xc3\xbf\xc3\xa1\xc3\xab\xc3\xbb\xc3\xad\xc3\xbf \xc3\xa3\xc3\xb0\xc3\xae\xc3\xac\xc3\xb3'
Run Code Online (Sandbox Code Playgroud)

(例如,当您需要将其保存为UTF-8编码文件时,这是您在所有处理结束时所做的事情).

如果您的输入使用不同的编码,那么反过来说:

>>> d = "Schoßhündchen"                 # native encoding: cp850
>>> d = "Schoßhündchen".decode("cp850") # decode from Windows codepage
>>> d                                   # into a Unicode string (now work with this!)
u'Scho\xdfh\xfcndchen'
>>> print d                             # it displays correctly if your shell knows the glyphs
Schoßhündchen
>>> d.encode("utf-8")                   # before output, convert to UTF-8
'Scho\xc3\x9fh\xc3\xbcndchen'
Run Code Online (Sandbox Code Playgroud)