wxpython输出控制台无法打印西里尔字母
尽管我在我的 .py 文件顶部写了 #coding=utf-8
,并且在把西里尔字母字符串传给控制台之前已经把它们转换成了 utf-8,但我还是遇到了这个错误:
文件 "C:\Python27\lib\encodings\cp1252.py",第 15 行,在解码时 返回 codecs.charmap_decode(input,errors,decoding_table) UnicodeDecodeError: 'charmap' 编解码器无法解码位置 16 的字节 0x90: 字符映射到
我还可以做些什么呢?
这是我的 to_utf8
函数:
def to_utf8(obj):
if isinstance(obj, dict):
return dict([(to_utf8(key), to_utf8(value)) for key, value in obj.iteritems()])
elif isinstance(obj, list):
return [to_utf8(element) for element in obj]
elif isinstance(obj, unicode):
return obj.encode('utf-8')
else:
return obj
2 个回答
0
首先,确保你使用的是wxPython的unicode版本。最新的版本只有unicode格式,但在wxPython 2.8(可能还有2.9)中,你可以找到ascii版本。如果你已经确认自己有unicode版本,那么你可能想快速浏览一下wxPython的维基百科:
- http://wiki.wxpython.org/Internationalization
- http://wxpython.org/Phoenix/docs/html/internationalization.html
- http://wiki.wxpython.org/RecipesI18n
这个教程也非常有用:
希望这些资源能帮助你解决问题。
2
你走错方向了:显然,你的 str
中的字节是 utf8
格式的。不过,Python 对 str
里面的内容并不在意(从 Python 的角度来看,UTF-8 编码的 Unicode 代码点只是一串字节而已)。
这个问题还没有答案:出于我不知道的原因,它试图解码成 cp1252
格式。
如果你把 utf8
明确地给 Python,它就能正常工作。同样地,如果你在字面量前加上 u
,Python 就知道这个字符序列里面是什么(现在它是 unicode
类型了)。str != unicode != utf8
。
# -*- coding: utf-8 -*-
import wx
# works
mystr= "СТАЛИНГРАД".decode('utf8')
# this also works
mystr= u"СТАЛИНГРАД"
# uncomment to make code fail
#mystr= "СТАЛИНГРАД"
app = wx.App(0)
frm = wx.Frame(None, -1, mystr)
frm.Show()
app.MainLoop())
wxPython 3.0 只支持 Unicode,接受 utf-8 和 Unicode。