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

相关推荐
开开心心_Every1 小时前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·网络·pdf·电脑·excel·依赖倒置原则
codeJinger11 小时前
【Python】操作Excel文件
python·excel
书到用时方恨少!15 小时前
Python Pandas 使用指南:数据分析的瑞士军刀
python·数据分析·pandas
城数派21 小时前
谷歌18亿建筑足迹数据集 Google Open Buildings V3
数据库·arcgis·信息可视化·数据分析·excel
绛橘色的日落(。・∀・)ノ1 天前
Pandas 第九章 分类数据
pandas
whatzhang0071 天前
在 macOS 上从零配置 Vim:开启语法高亮 + 安装 vim-polyglot + 设置 gruvbox 主题
macos·vim·excel
fengyehongWorld1 天前
Excel 杂项知识
excel
MediaTea1 天前
Pandas :索引机制与数据访问
pandas
开开心心就好2 天前
免费好用:PPT演示计时提醒工具
windows·计算机视觉·计算机外设·逻辑回归·excel·深度优先·csdn开发云
TRACER~852 天前
项目实战:pandas+pytest+allure+adb
adb·pandas·pytest