utf-8 unicode error python


new_text = text.decode('utf-8').replace('u00a0', ' ').replace('u00ad', ' ').replace('Â', ' ').replace('    ',' ').replace('   ', ' ').replace('  ', ' ').replace('u20b9',' ').replace('ufffd',' ').replace('u037e',' ').replace('u2022',' ').replace('u200b',' ').replace('0xc3',' ')

这是由以下代码产生的错误:

new_text = text.decode('utf-8').replace('u00a0', ' ').replace('u00ad', ' ').replace('Â', ' ').replace('    ',
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
127.0.0.1 - - [29/Aug/2017 15:22:00] "GET / HTTP/1.1" 500 -

我尝试过从unicode解码ascii。

您在unicode对象上调用.replace,但为其提供了str参数。参数将使用默认ASCII编码转换为unicode,对于不在范围(128(内的字节,该编码将失败。

为了避免这个问题,不要混合使用strunicode。将unicode参数传递给unicode方法:

new_text = text.decode('utf-8').replace(u'\u00a0', u' ').replace(u'\u00ad', u' ')...

或者在str对象中进行替换,假设textstr:

new_text = text.replace('u00a0', ' ').replace('u00ad', ' ')...

最后一块链式替换似乎是问题所在。

text.replace('0xc3', ' ')

THis将尝试用空格替换字节0xc3。在您的代码片段中,它有效地读取

text.decode('utf-8').replace('0xc3', ' ')

这意味着您首先在python中将字节解码为(unicode-(字符串,然后想要替换错误的字节。如果你在解码前替换字节,它应该会起作用:

text.replace('0xc3', ' ').decode('utf-8')

最新更新