【问题标题】:'ascii' codec can't decode byte 0xe2 in position 6723 Python 3.5“ascii”编解码器无法解码位置 6723 Python 3.5 中的字节 0xe2
【发布时间】:2017-10-19 02:05:46
【问题描述】:
text_file = open("university_towns.txt")
State = {idx: lines.decode('utf-8').strip().replace("[edit]", "") 
             for idx,lines in enumerate(text_file) if "edit" in lines}

我的代码出现错误:

'ascii' codec can't decode byte 0xe2 in position 6723    

我正在使用 Python 3.5。

【问题讨论】:

  • Python 2 还是 Python 3?
  • 看起来字节 6723 不是正确的 unicode。将errors='ignore' 传递给`decode()` 可能会有所帮助。
  • 在 python 3.x 中,由于您没有指定编码,因此文件以sys.getdefaultencoding() 所说的任何模式打开。 lines.decode('utf-8') 无效,因为 3.x 字符串没有 decode 方法,所以你没有走那么远,否则你会有不同的错误。我的猜测是问题出在enumerate(text_file)... 但这意味着您的默认编码是ascii。您可以逐行读取文件,看看是否会出现错误。

标签: python python-3.x utf-8 ascii decode


【解决方案1】:

从第二行删除 decode("utf-8) ,它可能会解决您的问题!

在 python 2 中,我们使用编码和解码来解决相关问题。但是在 python 3.x 中,str/bytes 也使用了类似的方法。

您不必阅读以下参考资料:

python-3-encode-decode-vs-bytes-str

希望,它有帮助!

【讨论】:

    猜你喜欢
    • 2015-01-26
    • 2013-12-05
    • 2018-08-21
    • 1970-01-01
    • 2011-06-29
    • 2014-02-10
    • 1970-01-01
    • 2013-09-10
    相关资源
    最近更新 更多