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

相关推荐
橙露7 小时前
Polars 极速数据框架:比 Pandas 更快的大数据处理
pandas
那个失眠的夜13 小时前
Spring 的纯注解配置
xml·java·数据库·后端·spring·junit
Yu_Lijing15 小时前
Python数据分析和数据处理库Pandas(Series篇)
人工智能·python·数据分析·pandas
AI效率工坊15 小时前
【Python实战】10万行数据自动清洗:pandas+AI智能识别+异常检测完整方案
人工智能·python·pandas
mobai717 小时前
使用pyang将yang模型转换为xml
xml·运维·服务器
人工干智能17 小时前
科普:pandas 中的类 SQL语句:transaction.groupby(“card_id“)[‘purchase_day‘].diff()
数据库·sql·pandas
herinspace17 小时前
管家婆实用帖-如何使用ping命令检测网络环境
网络·数据库·人工智能·学习·excel·语音识别
神秘剑客_CN18 小时前
python安装requests及pandas
开发语言·python·pandas
hard_coding_wang19 小时前
了解一个Excel批量替换的公式用法:REDUCE + LAMBDA 实现循环替换
开发语言·c#·excel
城数派19 小时前
2025年省市县三级的平均高程数据(Excel\Shp格式)
数据库·arcgis·信息可视化·excel