UnicodeDecodeError:“ascii”编解码器无法解码位置8中的字节0xea:序号不在范围(128)内

2024-05-19 11:02:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将从jobs API获取的数据写入Google电子表格。“latin-1”的后续编码将一直编码到第93页,但当达到94页时,它将异常。我使用了不同的以下技术,但“拉丁-1”实现了最大分页。其他的已经被评论过了(他们死在65页)。你能告诉我如何修改未注释的(例如,encode('latin-1'))以使199页安全地写在电子表格上吗? 代码如下: 在这方面的任何指导方针都是事先得到赞赏的。

  def append_data(self,worksheet,row,start_row, start_col,end_col):
    r = start_row #last_empty_row(worksheet)
    j = 0
    i = start_col
    while (i <= end_col):
        try:
            worksheet.update_cell(r,i,unicode(row[j]).encode('latin-1','ignore'))
            #worksheet.update_cell(r,i,unicode(row[j]).decode('latin-1').encode("utf- 
             16"))
            #worksheet.update_cell(r,i,unicode(row[j]).encode('iso-8859-1'))
            #worksheet.update_cell(r,i,unicode(row[j]).encode('latin-1').decode("utf-
            8"))
            #worksheet.update_cell(r,i,unicode(row[j]).decode('utf-8'))
            #worksheet.update_cell(r,i,unicode(row[j]).encode('latin-1', 'replace'))
            #worksheet.update_cell(r,i,unicode(row[j]).encode(sys.stdout.encoding,  
            'replace'))
            #worksheet.update_cell(r,i,row[j].encode('utf8'))
            #worksheet.update_cell(r,i,filter(self.onlyascii(str(row[j]))))      

        except Exception as e:  
            self.ehandling_obj.error_handler(self.ehandling_obj.SPREADSHEET_ERROR,[1])
            try:
                worksheet.update_cell(r,i,'N/A')
            except Exception as ee:
                y = 23
        j = j + 1
        i = i + 1

Tags: self编码unicodecellupdatecolstartutf
1条回答
网友
1楼 · 发布于 2024-05-19 11:02:38

您正在对字节字符串值调用unicode(),这意味着Python必须首先将解码到Unicode:

>>> unicode('\xea')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xea in position 0: ordinal not in range(128)

正是这种解码失败,不是从Unicode返回字节字符串的编码。

您已经有Latin-1输入数据,或者应该使用适当的编解码器进行解码:

unicode(row[j], 'utf8').encode('latin1')

或者使用str.decode()

row[j].decode('utf8').encode('latin1')

我在这里选择UTF-8作为示例,您没有提供任何有关输入数据或其可能编码的详细信息。你需要自己在这里选择正确的编解码器。

相关问题 更多 >

    热门问题