【问题标题】:UnicodeDecodeError: invalid start byteUnicodeDecodeError:无效的起始字节
【发布时间】:2015-03-04 15:29:57
【问题描述】:

我有一个关于 UnicodeDecodeError:invalid start byte 的快速问题。 我认为我的文本中的某处有非 UTF-8 字符,但错误消息的位置是读取文件的起点,所以我不知道如何修复它。

如果您有任何建议,请告诉我

以下是我从 python 返回的错误信息。

for line in fi:
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/codecs.py", line 313, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte

以下是我的代码:

for filename in os.listdir(readDir):
    filename = os.path.join(readDir, filename)
    for keyword in keywords:
        outFileName = os.path.join(sortDir, keyword)
        outFileName = outFileName+'.csv'

        with open(filename, 'r') as fi, open(outFileName, "a") as fo:
            for line in fi:

【问题讨论】:

  • 我认为起始字符串有一个非 UTF-8 字符...我应该删除它吗?
  • 你的文件实际上是 UTF-8 还是别的什么?
  • 它是由JSON格式数据组成的文本文件
  • 我的意思是它可能包含非 UTF_8 格式的文本,因为它是从 Twitter 收集的
  • Json 文本是 unicode 文本。 utf-8 是 unicode 字符的字节编码。 utf-8(或多或少)强制用于 json 文本的序列化。如果源发送的字节未正确解码,则故障出在源。相当于发送有语法错误的python代码。除了通过肉眼检查文本(以二进制模式打开,读入一个字节对象,并使用errors='replace' 而不是“严格”进行解码)并猜测修复可能是什么之外,您无能为力。否则将try: except: 放在with 语句周围以跳过无效文件。

标签: python python-3.x unicode


【解决方案1】:

我遇到了同样的问题,搜索了一段时间后我做了什么

import sys

#Set default encoder 
sys.setdefaultencoding("ISO-8859-1")

#Then convert string to UTF-8
yourString.encode('utf-8').strip()

希望对大家有用

【讨论】:

  • 没有setdefaultencoding
猜你喜欢
  • 2021-06-15
  • 2011-07-29
  • 2022-06-29
  • 2014-04-08
  • 1970-01-01
  • 2013-10-02
  • 2016-11-25
相关资源
最近更新 更多