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

相关推荐
墨上烟雨15 小时前
Pandas 数据结构 - DataFrame
pandas
狮子也疯狂16 小时前
【天翼AI-星辰智能体平台】| 基于Excel表实现智能问数助手智能体开发实战
人工智能·oracle·excel
利刃大大1 天前
【Mybatis】Mybatis入门 && 基础操作 && XML配置文件开发 && 多表查询 && 注入问题 && 数据库连接池
xml·数据库·mybatis
倔强的小石头_1 天前
Python 从入门到实战(十):Pandas 数据处理(高效搞定表格数据的 “瑞士军刀”)
人工智能·python·pandas
梦幻通灵2 天前
Excel序列生成的4种方案实战
excel
万粉变现经纪人2 天前
Python系列Bug修复PyCharm控制台pip install报错:如何解决 pip install 网络报错 企业网关拦截 User-Agent 问题
网络·python·pycharm·beautifulsoup·bug·pandas·pip
Lucky高2 天前
Pandas库实践1_预备知识准备
python·pandas
墨上烟雨2 天前
Pandas 数据结构 - Series
数据结构·pandas
墨痕诉清风3 天前
java漏洞集合工具(Struts2、Fastjson、Weblogic(xml)、Shiro、Log4j、Jboss、SpringCloud)
xml·java·struts·安全·web安全·spring cloud·log4j
2501_930707783 天前
使用C#代码将 Excel 转换为 ODS,或将 ODS 转换为 Excel
excel