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

相关推荐
无心水42 分钟前
Python时间处理通关指南:datetime/arrow/pandas实战
开发语言·人工智能·python·pandas·datetime·arrow·金融科技
莫爷43 分钟前
JSON vs XML vs YAML 深度对比:如何选择合适的数据格式?
xml·前端·json
华科易迅43 分钟前
Spring AOP(XML后置+异常通知)
xml·java·spring
fanchenxinok1 天前
LIN矩阵Excel ⇄ LDF互转工具:打通设计数据与协议描述的关键桥梁
矩阵·excel·lin·ldf·excel和ldf互转
Predestination王瀞潞1 天前
6.3.1 软件->W3C XPath 1.0 标准(W3C Recommendation):XPath(XML Path Language)查询语言
xml·数据库·oracle
RE-19011 天前
Polars:告别 Pandas 性能瓶颈,用 Rust 驱动的 DataFrame 库处理亿级数据
开发语言·rust·pandas·polars·ai生成
拆房老料1 天前
多人协同编辑Excel时,筛选相互干扰怎么办?Onlyoffice中国版给出了与WPS一样的答案
编辑器·excel·开源软件·wps
Data-Miner1 天前
Excel-Agent:你的专属 AI 数据分析助手
人工智能·数据分析·excel
xcLeigh1 天前
告别 Excel 繁琐操作!Metabase让数据可视化触手可及
mysql·docker·信息可视化·excel·数据可视化·metabase·cpolar
葡萄城技术团队1 天前
Excel 2025 年度回顾:文化、匠心与 Copilot 开启的计算新纪元
excel·copilot