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

相关推荐
1314lay_10076 小时前
通过Sql Server创建EXCEL文件:master..xp_cmdshell
数据库·excel
2601_9623008111 小时前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
2601_9669496512 小时前
批量 K 线不只是提速:因子研究中的数据质量、复权与回测偏差
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
ms365copilot12 小时前
Excel Copilot一键美化图表,无需手动调格式
excel·copilot·outlook
2501_9336707913 小时前
内部审计校招的数据化趋势:SQL、Excel、Power BI和证书选择
数据库·sql·excel
weixin_493503671 天前
商会系统里的在线文件预览:PDF/Word/Excel 三种实现与选型(Node + 前端实战)
pdf·word·excel
liliangcsdn1 天前
IC计算-前向/远期收益计算和代码示例
开发语言·python·pandas
asdzx672 天前
Python 解析 Excel 数据、图片与图表的实现方案
python·excel
慧都小妮子2 天前
GcExcel 服务端 Excel 组件:无需安装 Office 的 Java/.NET 报表方案
java·.net·excel·gcexcel·服务端excel组件
The Future is mine2 天前
Excel如何只允许对部分表格内容进行修改
excel