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

我正在将从作业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 

你在一个字节unicode()上调用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回到字节string的编码。

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

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

或者使用str.decode()

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

我在这里selectUTF-8作为例子,你没有提供关于input数据或其可能的编码的任何细节。 你需要在这里select正确的编解码器。