Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Xml Python3中元素的解析和重新格式化_Xml_Python 3.x_Lxml_Python 3.4 - Fatal编程技术网

Xml Python3中元素的解析和重新格式化

Xml Python3中元素的解析和重新格式化,xml,python-3.x,lxml,python-3.4,Xml,Python 3.x,Lxml,Python 3.4,我有一些xml元素: <seg id="1" text="some text"/> 我想在python3中将其重新格式化为: <in_seg id="sent1"> some text</in_seg> 一些文本 我该怎么做 您可以通过实例化元素类来创建元素: from lxml.etree import fromstring, Element, tostring data = """ <seg id="1" text="some text"

我有一些xml元素:

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

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

<in_seg id="sent1"> some text</in_seg>
一些文本

我该怎么做

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

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))
从lxml.etree导入fromstring、Element、tostring
data=”“”
"""
元素=fromstring(数据)
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=标记_text
打印(tostring(新元素))
印刷品:

<in_seg id="sent1">some text</in_seg>
一些文本