UnicodeDecodeError: 'utf8'编解码器无法解码位置0处的字节0xc3:数据意外结束。

4

我正在编写一个用于对推文进行词干提取的代码,但在编码时遇到了编码问题。当我尝试应用Porter词干提取器时,它显示出错。可能是我没有正确对其进行分词处理。

我的代码如下...

import sys
import pandas as pd
import nltk
import scipy as sp
from nltk.classify import NaiveBayesClassifier
from nltk.stem import PorterStemmer
reload(sys)  
sys.setdefaultencoding('utf8')


stemmer=nltk.stem.PorterStemmer()

p_test = pd.read_csv('TestSA.csv')
train = pd.read_csv('TrainSA.csv')

def word_feats(words):
    return dict([(word, True) for word in words])

for i in range(len(train)-1):
    t = []
    #train.SentimentText[i] = " ".join(t)
    for word in nltk.word_tokenize(train.SentimentText[i]):
        t.append(stemmer.stem(word))
    train.SentimentText[i] = ' '.join(t)

当我尝试执行时,返回错误:
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-10-5aa856d0307f> in <module>()
     23     #train.SentimentText[i] = " ".join(t)
     24     for word in nltk.word_tokenize(train.SentimentText[i]):
---> 25         t.append(stemmer.stem(word))
     26     train.SentimentText[i] = ' '.join(t)
     27 

/usr/lib/python2.7/site-packages/nltk/stem/porter.pyc in stem(self, word)
    631     def stem(self, word):
    632         stem = self.stem_word(word.lower(), 0, len(word) - 1)
--> 633         return self._adjust_case(word, stem)
    634 
    635     ## --NLTK--

/usr/lib/python2.7/site-packages/nltk/stem/porter.pyc in _adjust_case(self, word, stem)
    602         for x in range(len(stem)):
    603             if lower[x] == stem[x]:
--> 604                 ret += word[x]
    605             else:
    606                 ret += stem[x]

/usr/lib64/python2.7/encodings/utf_8.pyc in decode(input, errors)
     14 
     15 def decode(input, errors='strict'):
---> 16     return codecs.utf_8_decode(input, errors, True)
     17 
     18 class IncrementalEncoder(codecs.IncrementalEncoder):

UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 0: unexpected end of data

有人知道我的代码哪里出了问题吗?我被卡在这个错误上了。有什么建议吗?


相关链接:https://dev59.com/LmIj5IYBdhLWcg3w_5vl 和 https://dev59.com/zmcs5IYBdhLWcg3w8oTK - alvas
为了更精确地帮助您,您能否在线发布数据集或样本。如果没有看到数据,就很难知道出了什么问题。 - alvas
除非您能看到并知道数据的确切编码方式,否则了解文本的类型是没有帮助的。 - alvas
看起来你很可能在处理ASCII之外的Latin-1编码,通过正确地将其编码/解码为UTF8,你可能会解决问题,但是如果没有看到数据,只能随机猜测发生了什么 =( - alvas
另外,请注意sys.setdefaultencoding()的“罪恶”: https://dev59.com/TW865IYBdhLWcg3wat2l - alvas
显示剩余3条评论
1个回答

3
我认为关键的一行是604,就在引发错误的位置上面一帧:
--> 604                 ret += word[x]

可能ret是Unicode字符串,而word是字节字符串。然而你不能像那个循环一样一个字节一个字节地解码UTF-8。

问题在于read_csv返回的是字节,而你正在对这些字节进行文本处理。这根本行不通,首先必须将这些字节解码为Unicode格式。我认为您可以使用:

pandas.read_csv(filename, encoding='utf-8')

如果可能的话,请使用Python 3。这样尝试连接字节和Unicode将始终引发错误,从而更容易发现这些问题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接