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

相关推荐
虎头金猫3 小时前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
Xiu Yan10 小时前
Python 数据分析:Pandas DataFrame 零基础入门教程
python·jupyter·pycharm·numpy·pandas
尤鸟倦12 小时前
OneNote table复制到Excel遇到的各种问题
excel
2601_966949651 天前
为什么量化回测中 for 循环比 DataFrame 慢三个数量级?从向量化原理讲起
开发语言·python·pandas·股票数据·quantdash
2501_930707781 天前
使用C#代码使用条件格式为 Excel 隔行设置颜色
c#·excel
Xiu Yan1 天前
Python 数据分析:Pandas Series 零基础入门教程
python·jupyter·pycharm·numpy·pandas
leihefeng1 天前
PX04-用 Python 读 Excel 画折线图,还能直接插回 Excel 文件
python·excel
yanlaifan1 天前
Excel中指定单元格不能输入内容的方法
excel
gCode Teacher 格码致知2 天前
Pandas教学-6:coerce详解
python·pandas
babe小鑫2 天前
信息与计算科学专业应届生面试 怎么证明自己能解决业务问题
学习·r语言·excel