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

相关推荐
流形填表8 小时前
大风车Excel|本地版软件下载与使用教程(2026最新版)
excel
流形填表19 小时前
大风车Excel|2026年最新消息
excel
星越华夏19 小时前
PPTX判断包含图表id
python·pandas
Cloud_Shy61821 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十一章 Python 包跟踪器 上篇)
python·数据分析·excel·pandas·matplotlib
丑八怪大丑21 小时前
XML_Tomcat_HTTP
xml·http·tomcat
Omics Pro1 天前
全流程可重复!R语言脂质组学:原始数据→功能解析
开发语言·人工智能·深度学习·语言模型·r语言·excel·知识图谱
开开心心就好1 天前
免费流畅的远程控制实用工具
linux·运维·服务器·网络·智能手机·excel
!chen1 天前
可视化Excel文档合并工具
excel
largecode2 天前
企业名称能在来电显示吗?号码显示公司名服务打通多终端展示
android·xml·ios·iphone·xcode·webview·phonegap
小郑加油2 天前
python学习Day14:实际应用——pandas的筛选与保存
python·学习·pandas