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

2024-06-10 14:04:11 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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))

Tags: 文件nameimport脚本sourcetargetmodelwith
1条回答
网友
1楼 · 发布于 2024-06-10 14:04:11

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

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>

相关问题 更多 >