为什么下面的项目失败了?为什么它成功与“拉丁-1”编解码器?

o = "a test of \xe9 char" #I want this to remain a string as this is what I am receiving
v = o.decode("utf-8")

结果是:

 Traceback (most recent call last):  
 File "<stdin>", line 1, in <module>  
 File "C:\Python27\lib\encodings\utf_8.py",
 line 16, in decode
     return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError:
 'utf8' codec can't decode byte 0xe9 in position 10: invalid continuation byte

当前回答

因为UTF-8是多字节的,并且没有对应于\xe9加上后面空格的组合的字符。

为什么它在utf-8和latin-1中都能成功?

下面是同一句话在utf-8中的用法:

>>> o.decode('latin-1').encode("utf-8")
'a test of \xc3\xa9 char'

其他回答

无效UTF-8。该字符是ISO-Latin1中的e-锐角字符,这就是它成功使用该代码集的原因。

如果你不知道你接收字符串的代码集,你就有麻烦了。最好是为您的协议/应用程序选择一个代码集(最好是UTF-8),然后您就拒绝那些没有解码的代码集。

如果你不能这样做,你就需要启发式。

因为UTF-8是多字节的,并且没有对应于\xe9加上后面空格的组合的字符。

为什么它在utf-8和latin-1中都能成功?

下面是同一句话在utf-8中的用法:

>>> o.decode('latin-1').encode("utf-8")
'a test of \xc3\xa9 char'

在二进制中,0xE9看起来像1110 1001。如果您在Wikipedia上阅读有关UTF-8的内容,就会看到这样的字节后面必须跟两个10xx xxxx形式的字节。举个例子:

>>> b'\xe9\x80\x80'.decode('utf-8')
u'\u9000'

但这只是异常的机械原因。在本例中,您的字符串几乎肯定是用latin 1编码的。你可以看到UTF-8和latin 1看起来有什么不同:

>>> u'\xe9'.encode('utf-8')
b'\xc3\xa9'
>>> u'\xe9'.encode('latin-1')
b'\xe9'

(注意,这里我混合使用了Python 2和Python 3的表示法。输入在任何版本的Python中都是有效的,但Python解释器不太可能以这种方式同时显示unicode和字节字符串。)

当我试图通过pandas.read_csv打开CSV文件时,我遇到了同样的错误 方法。

解决方案是将编码改为latin-1:

pd.read_csv('ml-100k/u.item', sep='|', names=m_cols , encoding='latin-1')

当你在pandas中输入一个特定的文件或数据时,这种类型的错误就会出现:-

data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv)

错误显示如下:- UnicodeDecodeError: 'utf-8' codec不能解码字节0xf4在位置1:无效的延续字节

因此,为了避免这种类型的错误,可以通过添加参数来删除

data=pd.read_csv('/kaggle/input/fertilizers-by-product-fao/FertilizersProduct.csv', encoding='ISO-8859-1')