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

相关推荐
ms365copilot7 小时前
Excel 新模型Claude Opus 5
人工智能·excel
CodexDave8 小时前
Python 自动化接单实战(二):Excel 批量清洗如何把规则与异常分开
python·自动化·excel·python自动化·数据处理·excel清洗·异常报告
蓝创工坊Blue Foundry9 小时前
发票、凭证和对账单怎么整理成 Excel?先定义字段,再逐项复核
pdf·ocr·excel·文心一言·paddlepaddle
ms365copilot10 小时前
Copilot直接读取Excel,一键生成完整数据汇报PPT
powerpoint·excel·copilot
石马马户1 天前
excel中使用宏绘制折线图
excel
Y3815326621 天前
serpbase + Pandas + Jupyter 数据分析实战
jupyter·数据分析·pandas
tedcloud1231 天前
Orca 部署指南:开源 AI 推理服务的 Linux 部署实践
linux·运维·服务器·人工智能·开源·自动化·excel
星雨流星天的笔记本2 天前
0.0用excel拆分数据
excel
元Y亨H2 天前
numpy与pandas 的介绍
numpy·pandas
蓝创工坊Blue Foundry2 天前
PaddleOCR 本地部署教程:小模型 OCR 如何完成字段提取到 Excel
pdf·自动化·ocr·excel·paddlepaddle·paddle