【问题标题】:parsing and reformatting elements in Python3在 Python3 中解析和重新格式化元素
【发布时间】:2014-11-30 16:16:38
【问题描述】:

我有一些带有元素的 xml:

<seg id="1" text="some text"/>

我想在 python3 中重新格式化为:

<in_seg id="sent1"> some text</in_seg>

我该怎么做?

【问题讨论】:

    标签: xml python-3.x lxml python-3.4


    【解决方案1】:

    您可以通过实例化 Element 类来创建元素:

    from lxml.etree import fromstring, Element, tostring
    
    data = """
    <seg id="1" text="some text"/>
    """
    element = fromstring(data)
    
    tag_name = 'in_' + element.tag
    tag_id = 'sent' + element.attrib['id']
    tag_text = element.attrib['text']
    
    new_element = Element(tag_name, attrib={'id': tag_id})
    new_element.text = tag_text
    print(tostring(new_element))
    

    打印:

    <in_seg id="sent1">some text</in_seg>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 2012-06-07
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2017-08-13
      相关资源
      最近更新 更多