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

相关推荐
星雨流星天的笔记本5 小时前
0.0用excel拆分数据
excel
元Y亨H11 小时前
numpy与pandas 的介绍
numpy·pandas
蓝创工坊Blue Foundry16 小时前
PaddleOCR 本地部署教程:小模型 OCR 如何完成字段提取到 Excel
pdf·自动化·ocr·excel·paddlepaddle·paddle
wujian831118 小时前
怎么用AI做excel表格 AI导出鸭来救场
人工智能·ai·excel·豆包·deepseek·ai导出鸭
用户2986985301418 小时前
React 前端处理 Excel 工作表复制的技术实践
javascript·react.js·excel
蓝创工坊Blue Foundry1 天前
个人藏书太多怎么整理?用 OCR 字段提取汇总成电子书目
pdf·ocr·excel·文心一言·paddlepaddle·paddle
小大宇2 天前
python pandas dataFrame sqlAlchemy案例
python·pandas
蓝创工坊Blue Foundry2 天前
扫描件批量转 Excel:先确认要整表还原还是字段汇总
python·pdf·ocr·excel
Dylan的码园2 天前
从Excel到数据库:数据分析全流程与Kettle ETL实战指南
数据库·数据分析·excel
元Y亨H2 天前
Pandas 解析 Excel 导致的内存溢出(MemoryError)
python·excel