我在文档中找到了这个解决方案的关键:
Using XPath to find text
特别是
is_text
和
is_tail
特性
_ElementUnicodeResult
.
使用这些属性,我可以判断是否需要更新
.text
或
.tail
父母的财产
_Element
.
这是一个有点棘手的理解,因为当你使用
getparent()
在文本节点上(
_ElementUnicodeResult
)这是它之前兄弟的尾巴(
.is_tail == True
),前一个兄弟姐妹作为父代返回;不是真正的父母。
实例
python
import re
from lxml import etree
xml = """<doc>
<para>I think the only card she has <gotcha>is the</gotcha> Lorem card. We have so many things that we have to do
better... and certainly ipsum is one of them. When other <gotcha>websites</gotcha> give you text, they're not
sending the best. They're not sending you, they're <gotcha>sending words</gotcha> that have lots of problems
and they're <gotcha>bringing</gotcha> those problems with us. They're bringing mistakes. They're bringing
misspellings. They're typists⦠And some, <gotcha>I assume</gotcha>, are good words.</para>
</doc>
"""
def update_text(match, word_list):
if match in word_list:
return f"[{match}]"
else:
return match
root = etree.fromstring(xml)
keywords = {"ipsum", "is", "the", "best", "problems", "mistakes"}
for text in root.xpath("//text()"):
parent = text.getparent()
updated_text = re.sub(r"[\w]+", lambda match: update_text(match.group(), keywords), text)
if text.is_text:
parent.text = updated_text
elif text.is_tail:
parent.tail = updated_text
etree.dump(root)
输出
(转储到控制台)
<doc>
<para>I think [the] only card she has <gotcha>[is] [the]</gotcha> Lorem card. We have so many things that we have to do
better... and certainly [ipsum] [is] one of them. When other <gotcha>websites</gotcha> give you text, they're not
sending [the] [best]. They're not sending you, they're <gotcha>sending words</gotcha> that have lots of [problems]
and they're <gotcha>bringing</gotcha> those [problems] with us. They're bringing [mistakes]. They're bringing
misspellings. They're typists⦠And some, <gotcha>I assume</gotcha>, are good words.</para>
</doc>