【问题标题】:UnicodeDecodeError: 'utf8' codec can't decode byte 0xb5 in position 894: invalid start byteUnicodeDecodeError:“utf8”编解码器无法解码位置 894 中的字节 0xb5:无效的起始字节
【发布时间】:2015-05-08 06:46:38
【问题描述】:

我正在为一个项目使用scikit-learn。在执行特征提取(working_with_text_data 教程)时,我得到 UnicodeDecodeError: 'utf8' codec can't decode byte。

使用 python 2.7.8 并使用 make 构建 scikit-learn

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(dataset.data)
print(X_train_counts.shape)

请帮忙解决一下?

【问题讨论】:

  • 你能告诉我们回溯吗? dataset.data 里有什么?显然其中一个输入数据是不允许的字符。
  • 您可能想尝试使用编解码器 utf-8-sig 加载数据。该文件可能具有为前三个字节定义的 utf-8 签名,或者在读取时跳过前 3 个字节。
  • 检查您正在加载的文件是否以 utf8 编码。可能是另一种编码。
  • 正如你所说的,这是编码的问题。我直接使用了'from sklearn.datasets import fetch_20newsgroups',它可以工作。如果我使用“from sklearn.datasets import load_files”来加载文件,它就不起作用。我想如果我改变我的文件编码,它将使用加载文件工作。谢谢。

标签: python utf-8 scikit-learn


【解决方案1】:

使用 load_files 函数时,编码应为 latin1

twenty_train = load_files('path/to/folder',encoding='latin1')

在 sklearn/datasets/twenty_newscroups.py 中

function _download_20newsgroups
...
load_files(train_path, encoding='latin1')

【讨论】:

    猜你喜欢
    • 2017-05-19
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2013-10-02
    • 2016-11-25
    • 2016-11-15
    • 2019-01-04
    相关资源
    最近更新 更多