合并标记(从字符串列表)到

2024-04-24 03:37:23 发布

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

如果在列表[1]中有两个字符串,包含两个XML标记:

<example> this is cool</example>

以及

<example> this is cooler! </example> 

如何将两个标记合并为一个标记,使其看起来像这样:

<example> this is cool this is cooler! </example>

所以当我打印(列表[1])时,我得到:

<example> this is cool this is cooler! </example>

Tags: 字符串标记列表isexamplexmlthiscool
1条回答
网友
1楼 · 发布于 2024-04-24 03:37:23

我们必须找到这两个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'

好吧,我们可以创建一个新的解析的元素,它的标签与第一个相同:

>>> 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>'

相关问题 更多 >