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

相关推荐
aluluka4 小时前
Emacs折腾日记(十四)——buffer操作
编辑器·excel·emacs
oh,huoyuyan10 小时前
火语言RPA--Excel插入空行
excel·rpa
littleBoy77715 小时前
使用excel中的VBA合并多个excel文件
excel·vba
GW_Cheng17 小时前
easyexcel和poi同时存在版本问题,使用easyexcel导出excel设置日期格式
excel
_extraordinary_19 小时前
Linux权限(一)
android·linux·excel
hmywillstronger1 天前
【Excel】【VBA】根据内容调整打印区域
android·excel
oh,huoyuyan1 天前
火语言RPA--Excel删除内容
excel·rpa
失败尽常态5231 天前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
杜大哥2 天前
如何在WPS打开的word、excel文件中,使用AI?
人工智能·word·excel·wps
@LitterFisher2 天前
Excell 代码处理
前端·javascript·excel