解决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")

相关推荐
骆驼爱记录6 小时前
Word样式检查器使用指南
自动化·word·excel·wps·新人首发
wpyok1686 小时前
密钥检测错误代码xml构建
xml
林开落L6 小时前
从入门到了解:Protobuf、JSON、XML 核心解析(C++ 示例)
xml·c++·json·protobuffer·结构化数据序列化机制
数研小生7 小时前
亚马逊商品列表API详解
前端·数据库·python·pandas
热爱生活的五柒7 小时前
wps office/word 表格左对齐后 文字前仍有空白,如何解决
excel
CS创新实验室9 小时前
Pandas 3 的新功能
android·ide·pandas
程序员敲代码吗9 小时前
在Excel中快速进行精确数据查找的方法
excel
介一安全21 小时前
【Web安全】XML注入全手法拆解
xml·web安全·安全性测试
CodeToGym1 天前
【Java 办公自动化】Apache POI 入门:手把手教你实现 Excel 导入与导出
java·apache·excel
qq_297574671 天前
【实战】POI 实现 Excel 多级表头导出(含合并单元格完整方案)
java·spring boot·后端·excel