【问题标题】:Transform XML to latex using python使用 python 将 XML 转换为 Latex
【发布时间】:2022-11-14 17:48:25
【问题描述】:

有没有办法使用python在XML中元素的开始和结束处插入文本

或使用 python 插入文本的任何配置文件

例如: 输入:

<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or <a href="http://example.com/">example.com</a>.</p>
    </body>
</html>

输出:

<html>
    <head>
        <title>Example page</title>
    </head>
    <body>
        <p>Moved to <a href="http://example.org/">example.org</a>
        or linktag{<a href="http://example.com/">example.com</a>}.</p>
    </body>
</html>
import xml.etree.ElementTree as ET  
tree = ET.parse('index.html')  
root = tree.getroot()  
  
for val in root.findall("./book/[price='5.95']"):  
    print(val.attrib)

for elem in root.findall("body/p/a"):   
    elem.tag = "linktag{"

tree.write("output.xhtml")

尝试但没有得到预期的输出

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以使用re(正则表达式)。例如,您可以在linktag{..} 中包含以下所有链接:

    import re
    
    replace_pattern = re.compile(r"(<a.*?</a>)")
    
    with open("output.html", "w") as fo:
        with open("index.html", 'r') as fi:
            for line in fi:
                fo.write(re.sub(replace_pattern, r"linktag{}", line))
    

    输出:

    <html>
        <head>
            <title>Example page</title>
        </head>
        <body>
            <p>Moved to linktag{<a href="http://example.org/">example.org</a>}
            or linktag{<a href="http://example.com/">example.com</a>}.</p>
        </body>
    </html>
    

    请注意,这不适用于复杂/嵌套的标签,正则表达式不适合这些标签。但由于您的输出不是有效的 XML/HTML,ET 在这里无法帮助您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 2010-09-16
      • 2016-12-21
      相关资源
      最近更新 更多