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

相关推荐
ID_180079054734 小时前
日本乐天商品详情API接口的请求构造与参数说明
开发语言·python·pandas
UR的出不克5 小时前
使用 Python 爬取 Bilibili 弹幕数据并导出 Excel
java·python·excel
wtsolutions5 小时前
Understanding Excel Data Formats - What Excel to JSON Supports
ui·json·excel
ぁず5 小时前
excel想生成一列随机数并删除公式保留值
excel
智航GIS8 小时前
11.13 Pandas进阶:掌握多级分组与高级聚合,解锁数据分析新维度
数据挖掘·数据分析·pandas
wtsolutions8 小时前
Real-World Use Cases - How Organizations Use Excel to JSON
json·github·excel
一只小H呀の8 小时前
pandas处理excel数据
excel·pandas
wregjru8 小时前
【操作系统】3.开发工具
excel
wtsolutions11 小时前
MCP Service Integration - Excel to JSON for AI and Automation
人工智能·json·excel
智航GIS1 天前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas