gpt4 book ai didi

python - 过滤掉python中的某些字节

转载 作者:太空狗 更新时间:2023-10-29 17:11:26 27 4
gpt4 key购买 nike

我在我的 python 程序中遇到了这个错误:ValueError: All strings must be XML compatible: Unicode or ASCII, no NULL bytes or control characters

这个问题,random text from /dev/random raising an error in lxml: All strings must be XML compatible: Unicode or ASCII, no NULL bytes , 解释了这个问题。

解决方案是过滤掉某些字节,但我对如何去做感到困惑。

有什么帮助吗?

编辑:抱歉,如果我没有提供有关该问题的足够信息。字符串数据来自外部 api 查询,我无法控制数据的格式。

最佳答案

正如链接问题的答案所说,XML 标准将有效字符定义为:

Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

将其翻译成 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
)

然后您可以根据需要使用该功能,例如

cleaned_string = ''.join(c for c in input_string if valid_xml_char_ordinal(c))

关于python - 过滤掉python中的某些字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8733233/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com