繁体   English   中英

如何防止 python BeautifulSoup 用十六进制代码替换转义序列?

[英]How to prevent python BeautifulSoup from replacing escape sequences with hex codes?

我正在尝试在 python 脚本中使用 BeautifulSoup 来帮助我避免在 IBM IDA(Infosphere Data Architect)ldm(逻辑数据模型)文件中进行手动工作,这些文件实际上是 Z0F635D0E0F3874FFF8B581C132 除了一些副作用外,它对我来说很好。 xml 中的 description 属性可以包含一些格式,其中控制字符编码为转义序列,如&#xD&#xA&#x9 在我的脚本中的 output 上,它们被转换为十六进制0D 0A 09 我不知道如何避免它。 为了说明效果,我简化了我的脚本,使它只读取 model 并将其写入另一个文件。

from bs4 import BeautifulSoup
#import os

source_modlel_file_name="TestModel.ldm"
target_model_file_name="TestModel_out.ldm"

with open(source_modlel_file_name,'r',encoding="utf-8",newline="\r\n") as source_model_file:
    source_model = source_model_file.read()

soup_model=BeautifulSoup(source_model, "xml")

with open(target_model_file_name, "w",encoding="utf-8",newline="\r\n") as file:
    file.write(str(soup_model))

一种解决方案是使用自定义格式化程序:

from bs4 import BeautifulSoup
from bs4.formatter import HTMLFormatter


class CustomAttributes(HTMLFormatter):
    def attributes(self, tag):
        for k, v in tag.attrs.items():
            v = v.replace("\r", "
")
            v = v.replace("\n", "
")
            v = v.replace("\t", "	")
            yield k, v


xml_doc = """<test>
    <data description="Some Text &#xD; &#xA; &#x9;">
        some data
    </data>
</test>"""

soup = BeautifulSoup(xml_doc, "xml")

print(soup.prettify(formatter=CustomAttributes()))

印刷:

<?xml version="1.0" encoding="utf-8"?>
<test>
 <data description="Some Text &#xD; &#xA; &#x9;">
  some data
 </data>
</test>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM