我正在把一堆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
我试过:
什么都不管用。有什么想法吗?
这可能不相关,但下面是您想知道的代码:
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)
正如我在邮件列表中所说,使用
charset_error
选项并将其设置为ignore
可能是最简单的。 如果文件实际上是utf-16,也可以在矢量器中将字符集设置为utf-16。 请参阅docs。这将解决您的问题:
从那一刻起,txt就是unicode格式,你可以在代码中的任何地方使用它。
如果要在处理后生成UTF-8文件,请执行以下操作:
您可以将csv文件行转储到json文件中,而不会出现以下任何编码错误:
相关问题 更多 >
编程相关推荐