Tri*_*daz 6 python unicode-string
这条线
data = get_url_contents(r[0]).encode('ascii', 'ignore')
Run Code Online (Sandbox Code Playgroud)
产生这个错误
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 11450: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
为什么?我假设因为我使用'忽略',在将输出保存为字符串变量的值时,不可能有解码错误.
由于 Python 2 的一个怪癖,您可以调用encode字节字符串(即已经编码的文本)。在这种情况下,它首先尝试通过使用 ascii 解码将其转换为 unicode 对象。因此,如果 get_url_contents 返回一个字节字符串,则您的行实际上会执行以下操作:
get_url_contents(r[0]).decode('ascii').encode('ascii', 'ignore')
Run Code Online (Sandbox Code Playgroud)
在Python 3中,字节字符串没有encode方法,因此同样的问题只会导致AttributeError。
(当然,我不知道这就是问题所在 - 它可能与功能有关get_url_contents。但我上面描述的是我最好的猜测)
| 归档时间: |
|
| 查看次数: |
9590 次 |
| 最近记录: |