UnicodeDecodeError: 'ascii' 编码无法解码位置8的字节0xea: 超出范围(128)
我正在将从工作API获取的数据写入Google电子表格。使用'latin-1'编码时,能够处理到第93页,但到了第94页就出错了。我尝试了不同的方法,但'latin-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
1 个回答
2
你在对一个字节字符串调用 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 作为例子,但你没有提供关于输入数据或其可能编码的详细信息。你需要自己选择合适的编码方式。