gpt4 book ai didi

python - 将元素合并在一起的正则表达式

转载 作者:行者123 更新时间:2023-12-03 21:00:41 25 4
gpt4 key购买 nike

使用 lxml 可以使用正则表达式将两个标签合并在一起吗?

<t1>test testing </t1>
<t1>testing non. </t1>

请注意,一个标签没有 [.] 只是想与第二个标签合并,
<t1>test testing testing non.</t>

可以通过使用 lxml regex 来解决这个问题吗?
tree.xpath('//t1/[.]')  #trying to figure out the regex to match together

最佳答案

我已经尝试了一些使用 lxml etree 和 XPath 的代码,希望这是您所需要的。不过,我需要做的是向 XML 添加一个“根”,然后我什至添加了第三个“t1”标签,并且 find 函数能够在“测试”中包含的所有 3 个标签中找到文本根。

from lxml import etree

xml = etree.XML("<tests><t1>test testing </t1><t1>testing non. </t1><t1>this is a random@ test</t1></tests>")

find = etree.XPath("//t1")

tests = find(xml)

tests_text = ''

for t in tests:
tests_text += t.text

print(tests_text)
我使用了 lxml 文档中的一些引用资料,您可以在此处找到 https://lxml.de/xpathxslt.html#the-xpath-method .
XPath 默认使用正则表达式,您只需要在“find”函数中指明您要在 XML 中查找哪个标签,在本例中为“//t1”。

关于python - 将元素合并在一起的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58044961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com