使用lxm插入包装子元素

2024-03-28 14:24:33 发布

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

我正在尝试在一个元素中插入一个子元素,该元素将具有与其前父元素相同的文本,因此是一个包装子元素。基本的例子就是我的输入:

<p>
    <s>text</s>
    <s>text</s>
    <s>text</s>
</p>

我想要这样的东西(anno的内容来自NLP工具,并不重要):

<p>
    <s>
        <orig>text</orig>
        <anno>token1</anno>
    </s>
    <s>
        <orig>text</orig>
        <anno>token2</anno>
    </s>
    <s>
        <orig>text</orig>
        <anno>token3</anno>
    </s>
</p>

anno元素会更简单,但我没有得到的是在其中生成一个子元素,该元素包含以前的文本。你知道吗

使用不同的元素函数(addprevious、addnext、append、insert),我可以做如下事情:

    <s>text<orig/></s>
    <s>text<orig>text</orig></s>
    <orig><s>text</s></orig>

但这些都不是我想要的。我必须和你一起工作吗?在这种情况下,怎么做?谢谢!你知道吗


Tags: 工具函数text文本元素内容nlp例子
1条回答
网友
1楼 · 发布于 2024-03-28 14:24:33

试试这个:

import sys

from lxml import etree

tree = etree.parse(open("/tmp/so.xml"))

# Make sure you have enough annos to match the existing <s> elements.
annos = ["token1", "token2", "token3"]

for i, s in enumerate(tree.xpath("//s")):
    # remember the text of the <s>
    text = s.text

    # remove the <s> from its parent
    parent = s.getparent()
    parent.remove(s)

    # create a new <s>
    new_s = etree.SubElement(parent, "s")

    # create the <orig>, set the remembered text on it
    orig = etree.SubElement(new_s, "orig")
    orig.text = text

    # create the <anon>, set the token on it
    annon = etree.SubElement(new_s, "anon")
    annon.text = annos[i]

with open("/tmp/out.xml", "wb") as f:
    tree.write(f, pretty_print=True)

输出:

<p>
  <s>
    <orig>text</orig>
    <anon>token1</anon>
  </s>
  <s>
    <orig>text</orig>
    <anon>token2</anon>
  </s>
  <s>
    <orig>text</orig>
    <anon>token3</anon>
  </s>
</p>

相关问题 更多 >