UnicodeEncodeError:“ascii”编解码器不能在位置126:序数不在范围(128)中编码字符u'\u2019'

时间:2020-12-08 20:21:31

Okay, I have read through many similar questions, and I believe I am following the advice correctly, but somehow my code is still not working.

好吧,我已经读了很多类似的问题,我相信我是正确的,但是我的代码仍然没有工作。

I have parsed an xml file. I have read on here that the output is now unicode. I am using the csv writer to write output to a file.

我已经解析了一个xml文件。我在这里已经读过,输出现在是unicode。我正在使用csv编写器将输出写入文件。

So, in my code I have tried to encode in utf-8 before using writerow. Why do I still get the error on writerow? My warning, "unicode!!!" does not get thrown until this error happens (I am running this on multiple files, and it works for most). Actually, though, I don't understand why the writerow is trying to use ascii, shouldn't it be expecting utf-8? I have replaced utf-8 with ascii in the encode function just for kicks. Same results. Please help!!!

因此,在我的代码中,我尝试在使用writerow之前对utf-8编码。为什么我在writerow上仍然有错误?我的警告:“unicode!!!”直到这个错误发生时才被抛出(我在多个文件上运行这个错误,而且它对大多数文件都有效)。实际上,我不明白为什么writerow会尝试使用ascii,难道它不应该期待utf-8吗?我已经用ascii码代替了utf-8,只是为了好玩。同样的结果。请帮助! ! !

        try:

           mystring=elem.find('./'+r2+'Description').text


           if isinstance(mystring, unicode):
               print("unicode!!!")
               mystring.encode('utf-8','ignore')
               datalist.append(mystring)
           else:    
               datalist.append(mystring)
        except AttributeError:
           datalist.append('No text')  

        c.writerow(datalist)

1 个解决方案

#1


9  

When you call mystring.encode(..., it's not changing the string in-place; it returns a new string.

当你叫mystring.encode(…它不会改变字符串的位置;它返回一个新字符串。

#1


9  

When you call mystring.encode(..., it's not changing the string in-place; it returns a new string.

当你叫mystring.encode(…它不会改变字符串的位置;它返回一个新字符串。