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

相关推荐
Zzq_Fighting2 小时前
Excel批量匹配数据
excel
E_ICEBLUE2 小时前
Python 实现 Excel 转 Markdown,支持工作表、单元格区域和批量处理
python·excel·markdown·格式转换
拆房老料3 小时前
ONLYOFFICE 集群部署实战:9.3 多实例方案与 9.4 架构变化
开源·word·excel·开源软件·ppt
ms365copilot5 小时前
Excel Copilot挖掘数据洞察,不用精通函数也能做数据分析 (1)
数据分析·excel·copilot
babe小鑫5 小时前
精算学专业秋招:Excel、SQL、R和Python应该先练什么
sql·r语言·excel
医疗信息化王工14 小时前
DataForge:基于 Python 的数据库批量导出 Excel 工具——从架构到部署的全流程实战
数据库·python·excel
1314lay_100721 小时前
通过Sql Server创建EXCEL文件:master..xp_cmdshell
数据库·excel
2601_962300811 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
2601_966949651 天前
批量 K 线不只是提速:因子研究中的数据质量、复权与回测偏差
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
ms365copilot1 天前
Excel Copilot一键美化图表,无需手动调格式
excel·copilot·outlook