Python:UnicodeDecodeError:'utf8'编解码器无法解码字节

15

我正在将一堆RTF文件读入Python字符串中。在某些文本中,我会遇到以下错误:

Traceback (most recent call last):
  File "11.08.py", line 47, in <module>
    X = vectorizer.fit_transform(texts)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line
716, in fit_transform
    X = super(TfidfVectorizer, self).fit_transform(raw_documents)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line
398, in fit_transform
    term_count_current = Counter(analyze(doc))
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line
313, in <lambda>
    tokenize(preprocess(self.decode(doc))), stop_words)
  File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line
224, in decode
    doc = doc.decode(self.charset, self.charset_error)
  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 0x92 in position 462: invalid
 start byte

我已经尝试过以下方法:
  1. 将文件的文本复制并粘贴到新文件中
  2. 将rtf文件保存为txt文件
  3. 使用Notepad++打开txt文件,选择“转换为utf-8”,并设置编码为utf-8
  4. 使用Microsoft Word打开文件并另存为新文件
但是以上方法都无效。你有什么想法吗?
可能与此无关,但以下是代码:
f = open(dir+location, "r")
doc = Rtf15Reader.read(f)
t = PlaintextWriter.write(doc).getvalue()
texts.append(t)
f.close()
vectorizer = TfidfVectorizer(sublinear_tf=True, max_df=0.5, stop_words='english')
X = vectorizer.fit_transform(texts)     

尝试使用X = vectorizer.fit_transform(texts.encode('utf-8')),如果我没记错的话,我总是搞不清何时使用.encode().decode(),只需尝试其中一个并查看发生了什么... - BrtH
不能工作。我认为这是实际文件的问题。 - Zach
尝试一下这个,但我不确定它是否有效。string = ''.join( [chr(ord(i)) for i in string]) - Squall
4个回答

10

这将解决您的问题:

import codecs

f = codecs.open(dir+location, 'r', encoding='utf-8')
txt = f.read()

从那一刻起,文本(txt)就以Unicode格式存在,并且你可以在代码中的任何地方使用它。

如果你想在处理后生成UTF-8文件,请执行以下操作:

f.write(txt.encode('utf-8'))

3
新的open()返回:Traceback (most recent call last): File "11.08.py", line 41, in <module> t = f.read() File "C:\Python27\lib\codecs.py", line 671, in read return self.reader.read(size) File "C:\Python27\lib\codecs.py", line 477, in read newchars, decodedbytes = self.decode(data, self.errors) UnicodeDecodeError: 'utf8'编解码器无法解码位置1266处的0x92字节,起始字节无效。 - Zach

6

如我在邮件列表中所说,最简单的方法可能是使用 charset_error 选项,并将其设置为 ignore。 如果文件实际上是 utf-16,则还可以在Vectorizer中将字符集设置为 utf-16。 请参见文档


1
最好明确了解文档语料库的字符集,并将其明确传递给TfidfVectorizer类,以避免潜在的静默解码错误,这可能导致最终分类准确性下降。 - ogrisel

4
您可以按照以下方式将csv文件行转储为json文件,而无需出现任何编码错误:
json.dump(row,jsonfile, encoding="ISO-8859-1")

2
最初的回答

请保留这行:

vectorizer = TfidfVectorizer(encoding='latin-1',sublinear_tf=True, max_df=0.5, stop_words='english')

对我而言,encoding='latin-1'起了作用。


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