【问题标题】:Parsing XML in Python在 Python 中解析 XML
【发布时间】:2018-01-27 17:23:58
【问题描述】:

我有一个很大的 XML 文件,我需要对其进行格式化以从其中的特定元素中获取一些所需的数据,并仅将所需的数据打印到另一个文件中。在 XML 文件中,我有许多文本标签,它们属于与 id 的不同对话,以及在作者标签之后有 id 的作者。我不需要所有作者的所有文本,只需要我有他们身份的特定作者。我如何编写一个函数,指定它只选择和写出作者 = id1 或 id2 或 id3.......等的对话? 这就是文档的样子……

 <conversations>
  <conversation id="e621da5de598c9321a1d505ea95e6a2d">
    <message line="1">
      <author>97964e7a9e8eb9cf78f2e4d7b2ff34c7</author>
      <time>03:20</time>
      <text>Hola.</text>
    </message>
    <message line="2">
      <author>0158d0d6781fc4d493f243d4caa49747</author>
      <time>03:20</time>
      <text>hi.</text>
    </message>
  </conversation>
  <conversation id="3c517e43554b6431f932acc138eed57e">
    <message line="1">
      <author>505166bca797ceaa203e245667d56b34</author>
      <time>18:11</time>
      <text>hi</text>
    </message>
    <message line="2">
  </conversation>
  <conversation id="3c517e43554b6431f932acc138eed57e">
     <author>505166bca797ceaa203e245667d56b34</author>
      <time>18:11</time>
      <text>Aujourd.</text>
    </message>
    <message line="3">
      <author>4b66cb4831680c47cc6b66060baff894</author>
      <time>18:11</time>
      <text>hey</text>
    </message>
  </conversation>

   </conversations> 

【问题讨论】:

  • 到目前为止你尝试过什么? StackOverflow 上有很多关于 Python 中 XML 解析的问题,其他地方也有很多示例。如果您可以向我们提供具体的技术问题,我们能否为您提供更好的答案(我试过 this 并且我希望它能够做到 that 但它却做了 something否则...)
  • 您的 xml 格式不正确第 21 行, 未关闭,第 33 行也是

标签: python xml xml-parsing html-xml-utils


【解决方案1】:
import xml.etree.ElementTree as ET
tree = ET.parse('conversations.xml')
for node in tree.iter():
    if node.tag == "conversations":
        continue
    if node.tag == "conversation":
        print("\n")  # visual break, new conversation
        print("{} {}".format(node.tag, node.attrib))
        continue
    if node.tag == "message":
        print("{} {}".format(node.tag, node.attrib))
        continue
    print("{} {}".format(node.tag, node.text))

所以使用上面你应该能够使用类似的逻辑检查 id 如果您正在搜索 97964e7a9e8eb9cf78f2e4d7b2ff34c7 等,请制作列表或字典。

authors = ['97964e7a9e8eb9cf78f2e4d7b2ff34c7']
for node in tree.iter():
    if node.tag == "author" and node.text in authors:
        print('found')

【讨论】:

  • 非常感谢 Diek,你是救生员。
  • @T.A 很高兴提供帮助,xml 可能会很痛苦。有时间请采纳答案,谢谢
  • 我实际上正在获取消息位置,例如:,如何取出节点标记和值并将其导出到将保存在我的文件中的文件计算机。谢谢 我真的不太了解 xml 和 etree。
  • 我实际上正在获取消息位置,例如:,如何取出节点标记和值并将其导出到将保存在我的文件中的文件计算机。谢谢我真的不太了解xml和etree。这实际上是我所做的:
  • 谢谢,我已经能够打印出节点标签和文本,但它没有遵循作者列表的条件,而是打印出所有可用的作者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多