我正在运行这个:
news_train = load_mlcomp('20news-18828', 'train')
vectorizer = TfidfVectorizer(encoding='latin1')
X_train = vectorizer.fit_transform((open(f, errors='ignore').read()
for f in news_train.filenames))但它得到了UnicodeDecodeError:'utf-8‘编解码器不能解码位置39的字节0xe4 :无效的继续字节。在open()函数。
我查过news_train.filenames了。它是:
array(['/Users/juby/Downloads/mlcomp/379/train/sci.med/12836-58920',
..., '/Users/juby/Downloads/mlcomp/379/train/sci.space/14129-61228'],
dtype='<U74')路径看起来是正确的。这可能与dtype或我的环境有关(我是Mac OSX 10.11),但在我尝试了很多次之后,我无法修复它。谢谢!
附言:这是来自http://scikit-learn.org/stable/auto_examples/text/mlcomp_sparse_document_classification.html#example-text-mlcomp-sparse-document-classification-py的ML教程
发布于 2016-07-30 04:07:24
好吧,我找到了解决方案。使用
open(f, encoding = "latin1")我不确定为什么它只发生在我的mac上。我很想知道。
发布于 2016-07-30 06:16:25
实际上,在Python中,open函数以默认模式'r'打开并读取文件,该模式将对文件内容进行解码(在大多数平台上,使用UTF-8)。因为您的文件是用latin1编码的,所以使用UTF8解码它们可能会导致UnicodeDecodeError。解决方案是以二进制模式('rb')打开文件,或者指定正确的编码(encoding="latin1")。
open(f, 'rb').read() # returns `byte` rather than `str`
# or,
open(f, encoding='latin1').read() # returns latin1 decoded `str`https://stackoverflow.com/questions/38664228
复制相似问题