解决pandas写入excel时的ValueError: All strings must be XML compatible报错

报错内容:

ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

报错背景

用pands批量写入excel文件,发生编码报错。检索了很多方案,都不能解决。

导致报错的原因是存在违法字符,不符合 XML 的解析规则。pandas写入应该是调用了xml的解析方法,所以这里也要符合xml的字符规则。

很多方法都是针对自己任务中遇到的特定违法字符进行的替换操作,不具备一般性。所以这里列出了一个最终解法------逐个字符的判断是否符合xml编译规则,只保留符合规则的编码。

最终代码

python 复制代码
def valid_xml_char_ordinal(c):
    codepoint = ord(c)
    # conditions ordered by presumed frequency
    return (
        0x20 <= codepoint <= 0xD7FF or
        codepoint in (0x9, 0xA, 0xD) or
        0xE000 <= codepoint <= 0xFFFD or
        0x10000 <= codepoint <= 0x10FFFF
        )


def wash_data(text):
    cleaned_string = ''.join(c for c in text if valid_xml_char_ordinal(c))
    return cleaned_string

text = "xxx"
text = wash_data(text)  # 完成清洗

参考

1\] [在python中过滤掉某些字节_python_Mangs-Python](https://devpress.csdn.net/python/6300a38e7e66823466196ace.html "在python中过滤掉某些字节_python_Mangs-Python")

相关推荐
小妖6661 小时前
excel 本地sheet往服务器上粘贴时,表格宽度没有粘过来
excel
智航GIS2 小时前
11.7 使用Pandas 模块中describe()、groupby()进行简单分析
python·pandas
yongui478345 小时前
使用C#实现Excel实时读取并导入SQL数据库
数据库·c#·excel
hanjq_code7 小时前
java使用阿里的easyExcel解决把excel每行的数据转成excel表格格式数据并打包成ZIP下载
java·开发语言·excel
人工干智能7 小时前
python的高级技巧:Pandas中的`iloc[]`和`loc[]`
开发语言·python·pandas
牛猫Data7 小时前
Power BI为什么不能完全取代Excel?
microsoft·数据分析·excel·database·数据可视化·powerbi
小当家.1057 小时前
《Java操作Excel实战教程:Apache POI从入门到精通》
java·apache·excel
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ9 小时前
mapper.xml中的大于等于、小于等于
xml
vortex51 天前
【小技巧】用 VLOOKUP 实现表格合并
excel
宫瑾1 天前
Excel常用操作记录
excel