【问题标题】:Python / Pandas: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 133: invalid continuation bytePython / Pandas:UnicodeDecodeError:'utf-8'编解码器无法解码位置133中的字节0xcd:无效的继续字节
【发布时间】:2018-07-26 12:36:06
【问题描述】:

我正在尝试构建一种方法来导入多种类型的 csv 或 Excel 并将其标准化。一切都运行顺利,直到某个 csv 出现,这给我带来了这个错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcd in position 133: invalid continuation byte

我正在构建一组 try/excepts 以包含数据类型的变体,但对于这个我不知道如何防止。

    if csv_or_excel_path[-3:]=='csv':
        try: table=pd.read_csv(csv_or_excel_path)
        except:
            try: table=pd.read_csv(csv_or_excel_path,sep=';')
            except:
                try:table=pd.read_csv(csv_or_excel_path,sep='\t')
                except:
                    try: table=pd.read_csv(csv_or_excel_path,encoding='utf-8')
                    except:
                        try: table=pd.read_csv(csv_or_excel_path,encoding='utf-8',sep=';')
                        except: table=pd.read_csv(csv_or_excel_path,encoding='utf-8',sep='\t')

顺便说一下,文件的分隔符是“;”。

所以:

a) 我知道如果我能确定“位置 133”中的字符是什么,那么追查问题会更容易,但我不知道如何找出来。有什么建议吗?

b) 有没有人建议在 try/except 序列中包含什么来跳过这个问题?

【问题讨论】:

  • 您能给我们看一个 CSV 样本吗?
  • @FHTMitchell 实际上我正在尝试复制/粘贴它,但是当我尝试这样做时,文本框会空白
  • 标题将是相关的,因为我认为它意味着文件中的第 133 个字符。它可能是“informação”中的角色之一。在加载之前,您需要先将文件转换为 UTF 格式。

标签: python pandas unidecoder


【解决方案1】:

另一种可能是做

with open(path_to_file, encoding="utf8", errors="ignore") as f:
    table = pd.read_csv(f, sep=";")

默认情况下,errors="ignore" 将忽略来自read() 调用的有问题的字节序列。您还可以为此类字节序列提供填充值。但总的来说,这应该可以减少大量痛苦的错误处理和嵌套的 try-excepts 的需要。

【讨论】:

    【解决方案2】:

    作为记录,这可能比多个try/excepts 更好

    def read_csv(filepath):
         if os.path.splitext(filepath)[1] != '.csv':
              return  # or whatever
         seps = [',', ';', '\t']                    # ',' is default
         encodings = [None, 'utf-8', 'ISO-8859-1']  # None is default
         for sep in seps:
             for encoding in encodings:
                  try:
                      return pd.read_csv(filepath, encoding=encoding, sep=sep)
                  except Exception:  # should really be more specific 
                      pass
         raise ValueError("{!r} is has no encoding in {} or seperator in {}"
                          .format(filepath, encodings, seps))
    

    【讨论】:

      【解决方案3】:

      感谢@woblers 和@FHTMitchell 的支持。问题是 CSV 有一个奇怪的编码:ISO-8859-1。

      我通过在 try/except 序列中添加几行来修复它。在这里你可以看到它的完整版本。

          if csv_or_excel_path[-3:]=='csv':
              try: table=pd.read_csv(csv_or_excel_path)
              except:
                  try: table=pd.read_csv(csv_or_excel_path,sep=';')
                  except:
                      try:table=pd.read_csv(csv_or_excel_path,sep='\t')
                      except:
                          try: table=pd.read_csv(csv_or_excel_path,encoding='utf-8')
                          except:
                              try: table=pd.read_csv(csv_or_excel_path,encoding='utf-8',sep=';')
                              except:
                                  try: table=pd.read_csv(csv_or_excel_path,encoding='utf-8',sep='\t')
                                  except:
                                      try:table=pd.read_csv(csv_or_excel_path,encoding = "ISO-8859-1", sep=";")
                                      except:
                                          try: table=pd.read_csv(csv_or_excel_path,encoding = "ISO-8859-1", sep=";")
                                          except: table=pd.read_csv(csv_or_excel_path,encoding = "ISO-8859-1", sep="\t")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-24
        • 1970-01-01
        • 2018-02-22
        • 2019-05-04
        • 1970-01-01
        • 2018-01-11
        • 2020-11-02
        • 2021-01-02
        相关资源
        最近更新 更多