我现在使用的是 Ubuntu 13.04 和 Python 2.7.4,并尝试运行包含以下几行的脚本:
html = unicode(html, 'cp932').encode('utf-8')
html1, html2 = html.split(some_text) # this line spits out the error
但是,当我在 Ubuntu 13.04 上运行上述脚本时,它吐出了错误 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 106: ordinal not in range(128)
。然而,这个完全相同的脚本始终可以在 OS X 10.8 和 Python 2.7.3 上成功执行。所以我想知道为什么错误只发生在两个平台之一......
我想到的第一个想法是,特别是在阅读这篇文章( UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1 )之后,二分法的出现是因为我处于不同的 LANG
中。环境,我使用jp_JP.UTF-8
在 OS X 上,但 en_US.UTF-8
在Ubuntu上。所以我还尝试添加一行 os.environ['LANG'] = 'jp_JP.UTF-8'
到上述脚本,但仍然遇到相同的错误。
一个更奇怪的现象是,当我尝试在 Ubuntu 上的 IPython shell 中运行脚本并在错误发生后立即进入 Debug模式,然后运行最初触发错误的行时,我没有得到错误更多...
那么这里发生了什么?我错过了什么?
提前致谢。
最佳答案
您没有向我们提供足够的信息来确定,但这很可能是您的问题:
如果some_text
是 unicode
对象,然后这一行:
html1, html2 = html.split(some_text) # this line spits out the error
…正在调用split
在str
上,并传递 unicode
范围。每当你混合str
和unicode
在同一调用中,Python 2.x 通过自动调用 unicode
来处理该问题关于str
。所以,这相当于:
html1, html2 = unicode(html).split(some_text) # this line spits out the error
...相当于:
html1, html2 = html.decode(sys.getdefaultencoding()).split(some_text) # this line spits out the error
...如果 html
中有任何非 ASCII 字符,则会失败,正如您所看到的那样。
简单的解决方法是显式编码 some_text
转为 UTF-8:
html1, html2 = html.split(some_text.encode('utf-8'))
但就我个人而言,我什至不会尝试与 str
合作来自 3 个不同字符集的对象都在同一个程序中。为什么不只是 decode
/encode
在最边缘,只需处理 unicode
物体之间到处都是?
关于python - ascii 编解码器无法在 Ubuntu/Python 中解码位置错误中的字节 0xe3,但在 OS X/Python 上则不行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17355395/