合并标签(从字符串列表)一起
问题描述:
如果在列表[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>
答
我们必须找到标签名称和两个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>'
所以,你有两个字符串列表? – brandizzi 2015-01-26 19:54:05
@brandizzi我有一个元素的列表,里面的元素有一个单一的字符串“这很酷 这是更酷! ” –
Jorge
2015-01-26 19:55:25
如果你说你有“标签”,我问什么样的标签? BeautifulSoup? ElementTree的? minidom命名?你使用的是什么xml/html分析器? – 2015-01-26 19:56:06