gpt4 book ai didi

python - lxml etree 获取元素之前的所有文本

转载 作者:行者123 更新时间:2023-11-30 23:09:40 28 4
gpt4 key购买 nike

如何将 etree 中元素之前的所有文本与该元素之后的文本分开?

from lxml import etree

tree = etree.fromstring('''
<a>
find
<b>
the
</b>
text
<dd></dd>
<c>
before
</c>
<dd></dd>
and after
</a>
''')

我想要什么?在此示例中,<dd>标签是分隔符,对于所有标签来说

for el in tree.findall('.//dd'):

我想要它们之前和之后的所有文本:

[
{
el : <Element dd at 0xsomedistinctadress>,
before : 'find the text',
after : 'before and after'
},
{
el : <Element dd at 0xsomeotherdistinctadress>,
before : 'find the text before',
after : 'and after'
}
]

我的想法是在树中使用某种占位符来替换 <dd>标签,然后在该占位符处剪切字符串,但我需要与实际元素的对应关系。

最佳答案

可能有更简单的方法,但我会使用以下 XPath 表达式:

preceding-sibling::*/text()|preceding::text()
following-sibling::*/text()|following::text()

示例实现(绝对违反了 DRY 原则):

def get_text_before(element):
for item in element.xpath("preceding-sibling::*/text()|preceding-sibling::text()"):
item = item.strip()
if item:
yield item

def get_text_after(element):
for item in element.xpath("following-sibling::*/text()|following-sibling::text()"):
item = item.strip()
if item:
yield item

for el in tree.findall('.//dd'):
before = " ".join(get_text_before(el))
after = " ".join(get_text_after(el))

print {
"el": el,
"before": before,
"after": after
}

打印:

{'el': <Element dd at 0x10af81488>, 'after': 'before and after', 'before': 'find the text'}
{'el': <Element dd at 0x10af81200>, 'after': 'and after', 'before': 'find the text before'}

关于python - lxml etree 获取元素之前的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31030382/

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