【问题标题】:How can I get a text with no tag in xml file by python如何通过python在xml文件中获取没有标签的文本
【发布时间】:2018-10-26 14:19:37
【问题描述】:
<?xml version='1.0' encoding='UTF-8'?>
<GateDocument>
<!-- The document content area with serialized nodes -->

<TextWithNodes><Node id="0" />Norway<Node id="6" /> <Node id="7" 
/>to<Node id="9" /> <Node id="10" />'<Node id="11" />completely<Node 
id="21" /> <Node id="22" />ban<Node id="25" /> <Node id="26" 
/>petrol<Node id="32" /> <Node id="33" />powered<Node id="40" /> <Node 
id="41" />cars<Node id="45" /> <Node id="46" />by<Node id="48" /> <Node 
id="49" />2025<Node id="53" />'<Node id="54" />.<Node id="55" /> . 
</TextWithNodes>
</GateDocument>

从上面的 XML 文件中,您可以注意到“TextWithNodes”标签中的单词没有标签。例如,我如何通过 python 获取“汽油动力汽车”文本

谢谢

【问题讨论】:

  • 展示你自己解决问题的努力和代码(问题中格式正确的文本)
  • 另一种不使用互文的替代方法是使用更难的模式。 (?!\>)[^"\s]+(?=\ regex101.com/r/7ZByy7/2

标签: python regex xml


【解决方案1】:

在findall()找到你想要的节点后可以使用itertext()方法:

from xml.etree import ElementTree as ET
x = '''<?xml version='1.0' encoding='UTF-8'?>
<GateDocument>
<!-- The document content area with serialized nodes -->

<TextWithNodes><Node id="0" />Norway<Node id="6" /> <Node id="7"
/>to<Node id="9" /> <Node id="10" />'<Node id="11" />completely<Node
id="21" /> <Node id="22" />ban<Node id="25" /> <Node id="26"
/>petrol<Node id="32" /> <Node id="33" />powered<Node id="40" /> <Node
id="41" />cars<Node id="45" /> <Node id="46" />by<Node id="48" /> <Node
id="49" />2025<Node id="53" />'<Node id="54" />.<Node id="55" /> .
</TextWithNodes>
</GateDocument>'''
t = ET.fromstring(x)
print(''.join(t.findall('.//TextWithNodes')[0].itertext()))

这个输出:

Norway to 'completely ban petrol powered cars by 2025'. .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 2013-12-01
    • 2016-05-13
    • 2015-04-17
    • 2017-08-13
    相关资源
    最近更新 更多