【问题标题】:Minidom - extracting sub-nodesMinidom - 提取子节点
【发布时间】:2017-02-10 10:16:45
【问题描述】:

我有一些 XML:

<sentence id="1086415:2">
 <text>$6 and there is much tasty food, all of it fresh and continually refilled.</text>
  <Opinions>
   <Opinion to="31" from="27" polarity="positive" category="FOOD#STYLE_OPTIONS" target="food"/>
   <Opinion to="31" from="27" polarity="positive" category="FOOD#QUALITY" target="food"/>
   <Opinion to="31" from="27" polarity="positive" category="FOOD#PRICES" target="food"/>
  </Opinions>
</sentence>
<sentence id="1086415:3">
 <text>I am not a vegetarian but, almost all the dishes were great.</text>
  <Opinions>
   <Opinion to="48" from="42" polarity="positive" category="FOOD#QUALITY" target="dishes"/>
  </Opinions>

我正在尝试提取 Opinions 标记中的所有内容,以将其与元组中的文本结合起来。我想知道如何用 minidom 做到这一点?目前意见返回'\n'。

from xml.dom import minidom
xmldoc = minidom.parse("ABSA16_Restaurants_Train_SB1_v2.xml")
sentences = xmldoc.getElementsByTagName("sentence")
for sentence in sentences:
   text = sentence.getElementsByTagName("text")[0].firstChild.data
   opinion = sentence.getElementsByTagName("Opinions")[0].firstChild.data

谢谢。

【问题讨论】:

    标签: python xml minidom


    【解决方案1】:

    你确定你需要minidom吗?

    来自文档:

    尚未精通 DOM 的用户应考虑 使用 xml.etree.ElementTree 模块进行 XML 处理 而是。

    如果没有充分的理由,请不要浪费您的时间并使用标准 python xml.etree.ElementTree,它的手册中有足够的示例来解决您的任务。如果遇到问题,请随时在 cmets 中询问。

    不仅如此,如果您需要经常使用 XML,我建议第三方 lxml,它是更强大的工具,包括一些电池。

    【讨论】:

      猜你喜欢
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 2012-09-22
      相关资源
      最近更新 更多