python3 'gbk' codec can't encode character '\uxxx' ‘\xa0’ in position x
程序员文章站
2022-03-31 19:14:39
...
pycharm IDE python3环境,想读取excel中的中文文本到文件中,在写文件的时候报错: python3 ‘gbk’ codec can’t encode character ‘\xa0’ in position
总结了一些会报错的中文unicode字符:
# doc = doc.replace('\xa0','')
# doc = doc.replace('\u2b50','')
# doc = doc.replace('\u30fb','')
# doc = doc.replace('\ufeff','')
# doc = doc.replace('\u200b','')
# doc = doc.replace('\u2003','')
# doc = doc.replace('\u2022','')
# doc = doc.replace('\u2002','')
# doc = doc.replace('\u201b','')
# doc = doc.replace('\u2ed8','')
# doc = doc.replace('\xa5','')
# doc = doc.replace('\u201a','')
# doc = doc.replace('\xbb','')
# doc = doc.replace('\u27a3','')
# doc = doc.replace('\ue60e','')
# doc = doc.replace('\ue607','')
# doc = doc.replace('\ue608','')
# doc = doc.replace('\ue60c','')
# doc = doc.replace('\ue609','')
但是总不能穷举吧。找了很多解决办法没有一个完全解决我的问题的TAT。。。
解决办法:
try:
fileXML.write(doc+"\n")
except Exception as e:
doc = doc.encode("GBK",'ignore').decode("GBK",'ignore')
fileXML.write(doc+"\n")
重点在这句:
doc = doc.encode(“GBK”,‘ignore’).decode(“GBK”,‘ignore’)
doc是一个字符串类型的变量,encode()结果是byte类型的串,不能直接作为write()函数的参数,所以要decode(),其中ignore变量就是忽略不能处理的字符。
有用的话给我点个赞吧~!
上一篇: Ubuntu14.04配置问题记录
推荐阅读
-
UnicodeEncodeError: 'gbk' codec can't encode character '\xe7' in position 10 解决乱码问题
-
解决Python3控制台输出的UnicodeEncodeError: ‘gbk‘ codec can‘t encode character ‘\u30fb‘ in position 0:问题
-
UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position ... 问题解决办法之一
-
编码问题:UnicodeEncodeError: 'gbk' codec can't encode character u'\xa0' in position 148:
-
PYTHON3解决'gbk' codec can't encode character '\xXX' in position XX
-
python3 'gbk' codec can't encode character '\uxxx' ‘\xa0’ in position x