将标签(来自字符串列表)合并在一起
Merging tags (from a list of strings) together
如果在列表[1]中我有两个字符串,包含两个 XML 标签:
<example> this is cool</example>
和
<example> this is cooler! </example>
我怎样才能将两个标签合并为一个标签,使其看起来像这样:
<example> this is cool this is cooler! </example>
所以当我执行 print(list[1]) 时,我得到:
<example> this is cool this is cooler! </example>
我们必须找到两个 XML 元素的 标签名称 和 文本 。为此,最好的办法是 解析 元素。
所以,你有这样一张清单,对吗?
>>> l = ['<example>this is cool</example>', '<example>this is cooler</example>']
首先,让我们解析它(在本例中为lxml
):
>>> import lxml.etree
>>> elements = [lxml.etree.fromstring(s) for s in l]
现在我们有一个包含两个元素的列表。从这些元素中,我们可以得到它们的标签名称...
>>> elements[0].tag
'example'
...及其文字内容:
>>> elements[0].text
'this is cool'
>>> elements[1].text
'this is cooler'
好吧,我们可以创建一个新的 parsed 与第一个标签相同的元素:
>>> new_element = new_element = lxml.etree.Element(elements[0].tag)
现在,我们将这个新元素的文本设置为前两个元素的串联:
>>> new_element.text = elements[0].text + elements[1].text
现在,我们从元素对象中获取字符串表示形式:
>>> lxml.etree.tostring(new_element)
b'<example>this is coolthis is cooler</example>'
如果在列表[1]中我有两个字符串,包含两个 XML 标签:
<example> this is cool</example>
和
<example> this is cooler! </example>
我怎样才能将两个标签合并为一个标签,使其看起来像这样:
<example> this is cool this is cooler! </example>
所以当我执行 print(list[1]) 时,我得到:
<example> this is cool this is cooler! </example>
我们必须找到两个 XML 元素的 标签名称 和 文本 。为此,最好的办法是 解析 元素。
所以,你有这样一张清单,对吗?
>>> l = ['<example>this is cool</example>', '<example>this is cooler</example>']
首先,让我们解析它(在本例中为lxml
):
>>> import lxml.etree
>>> elements = [lxml.etree.fromstring(s) for s in l]
现在我们有一个包含两个元素的列表。从这些元素中,我们可以得到它们的标签名称...
>>> elements[0].tag
'example'
...及其文字内容:
>>> elements[0].text
'this is cool'
>>> elements[1].text
'this is cooler'
好吧,我们可以创建一个新的 parsed 与第一个标签相同的元素:
>>> new_element = new_element = lxml.etree.Element(elements[0].tag)
现在,我们将这个新元素的文本设置为前两个元素的串联:
>>> new_element.text = elements[0].text + elements[1].text
现在,我们从元素对象中获取字符串表示形式:
>>> lxml.etree.tostring(new_element)
b'<example>this is coolthis is cooler</example>'