关于UnicodeDecodeError: 'gbk' codec can't decode byte的解决办法

问题描述

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xae in position 199: illegal multibyte sequence

这个《机器学习实战》朴素贝叶斯算法中遇到的问题。

解决方案
  1. \email\ham中的23.txt中第二段多了一个®(使用记事本打开显示的是“?”),导致解码失败,删除‘®’之后便可以继续执行。
  2. 使用windows-1252编码的方式读取txt,open txt文档时加一条encoding='windows-1252'
    open('email/spam/%d.txt' % i, encoding="windows-1252").read()
问题分析

UnicodeDecodeError解释为Unicode的解码(decode)出现错误了,也就当前正在处理某种编码类型的字符串,是想要将该字符串去解码,变成Unicode,但是在解码的过程中发生错误了。
分别测试\email\ham\中的每一个txt文档,只有23.txt报错:

    ...: file = open('email\\ham\\23.txt')
    ...: fileRead = file.read()
    ...: wordList = bayes.textParse(fileRead)
    ...: docList.append(wordList)
    ...: fullText.extend(wordList)
    ...: classList.append(1)
    ...:
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-33-598ed4b80c9a> in <module>()
      1
      2 file = open('email\\ham\\23.txt')
----> 3 fileRead = file.read()
      4 wordList = bayes.textParse(fileRead)
      5 docList.append(wordList)

UnicodeDecodeError: 'gbk' codec can't decode byte 0xae in position 199: illegal
multibyte sequence

23.txt第二段(记事本打开“®”显示为“?”):
SciFinance® is a derivatives pricing and risk model development tool that automatically generates C/C++ and GPU-enabled source code from concise, high-level model specifications. No parallel computing or CUDA programming expertise is required.
使用gbk无法解码“®”,在sublime text中查看23.txt的编码方式为windows 1252,所以使用windows 1252的编码方式打开txt文档,程序便能够正常执行了。

  • 25
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值