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

相关推荐
2601_967980119 小时前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
用户03321266636712 小时前
使用 Python 轻松加密或解密 Excel 文档
python·excel
总裁余(余登武)2 天前
【python项目】:1操作EXCEl自动化开发
python·自动化·excel
benchmark_cc2 天前
单只股票五档盘口接入个人研究仓库:QuantDash 读取、校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
benchmark_cc3 天前
用 QuantDash 读取美股行情:AAPL.US 的运行前检查、排错顺序与数据校验清单
python·数据分析·pandas·量化交易·股票数据·quantdash
ailitsoft4 天前
库存管理系统如何记录跨门店调拨后的收货差异?
excel·零售·软件需求
百事牛科技5 天前
Excel的三种密码:防看、防存、防乱改,各管各的
windows·excel
databook5 天前
经常听到的透视表是干什么的?
python·数据分析·pandas
用户298698530145 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel
用户0332126663677 天前
使用 Python 在 Excel 文档中添加水印
python·excel