0

我有一个很大的 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> 
4

1 回答 1

0
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')
于 2017-08-19T03:59:32.597 回答