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

相关推荐
云和数据.ChenGuang12 小时前
基于鲲鹏 HPC 的 AI 对话机器人架构设计与技术实现
人工智能·数据分析·机器人·pandas·数据预处理·数据训练
Cloud_Shy61820 小时前
Python 数据分析基础入门:《Excel Python:飞速搞定数据分析与处理》学习笔记系列(第十二章 用户定义函数 中篇)
python·数据分析·excel·pandas
udc小白21 小时前
Excel实现LSTM示例
人工智能·深度学习·神经网络·机器学习·excel·lstm
沉下去,苦磨练!1 天前
python的数据分析Pandas
python·数据分析·pandas
码银1 天前
在若依框架中,使用easyExcel完成动态列导出
java·excel·ruoyi
开开心心就好1 天前
免费无广告的批量卸载与系统清理工具
linux·服务器·网络·智能手机·rabbitmq·excel·memcached
缘于自然81 天前
高通modem如何确认device_config.xml的使用路径
xml·modem·mbn·mcfg
SunnyDays10111 天前
Java 读写 Excel 公式:从基础到高级的实战总结
java·开发语言·excel
Codiggerworld2 天前
Vim配置从0到1:打造专属编辑器
编辑器·vim·excel
E_ICEBLUE2 天前
Python 教程:快速复制 Excel 工作表
python·excel