0

我想用 Python Etree 解析器解析和比较 2 个 XML 文件,如下所示:

我有 2 个包含大量数据的 XML 文件。一种是英文(源文件),另一种是对应的法文翻译(目标文件)。例如:

源文件:

<AB>
  <CD/>
  <EF>

    <GH>
      <id>123</id>
      <IJ>xyz</IJ>
      <KL>DOG</KL>
      <MN>dogs/dog</MN>
      some more tags and info on same level
      <metadata>
        <entry>
           <cl>Translation</cl>
           <cl>English:dog/dogs</cl>
        </entry>
        <entry>
           <string>blabla</string>
           <string>blabla</string>
        </entry>
            some more strings and entries
      </metadata>
    </GH>

  </EF>
  <stuff/>
  <morestuff/>
  <otherstuff/>
  <stuffstuff/>
  <blubb/>
  <bla/>
  <blubbbla>8</blubbla>
</AB>

目标文件看起来完全一样,但在某些地方没有文本:

<MN>chiens/chien</MN>
some more tags and info on same level
<metadata>
  <entry>
    <cl>Translation</cl>
    <cl></cl>
  </entry>

法语目标文件有一个空的跨语言参考,只要 2 个宏具有相同的 ID,我想将来自英语源文件的信息放入其中。我已经编写了一些代码,其中我用唯一的标签名称替换了字符串标签名称,以便识别跨语言引用。现在我想比较这 2 个文件,如果 2 个宏具有相同的 ID,则将法语文件中的空引用与英语文件中的信息交换。我之前尝试过 minidom 解析器,但卡住了,现在想尝试 Etree。我对编程几乎一无所知,并且觉得这很难。这是我到目前为止的代码:

    macros = ElementTree.parse(english)

    for tag in macros.getchildren('macro'):
        id_ = tag.find('id')
        data = tag.find('cl')
        id_dict[id_.text] = data.text

    macros = ElementTree.parse(french)

    for tag in macros.getchildren('macro'):
        id_ = tag.find('id')
        target = tag.find('cl')
        if target.text.strip() == '':
        target.text = id_dict[id_.text]

    print (ElementTree.tostring(macros))

我不仅一无所知,而且阅读其他关于此的帖子让我更加困惑。如果有人能启发我,我将不胜感激:-)

4

1 回答 1

1

可能还有更多细节需要澄清。这是带有一些调试打印的示例,显示了这个想法。它假定两个文件具有完全相同的结构,并且您只想在根目录下一层:

import xml.etree.ElementTree as etree

english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')

# Get the root elements, as they support iteration
# through their children (direct descendants)
english_root = english_tree.getroot()
french_root = french_tree.getroot()

# Iterate through the direct descendants of the root
# elements in both trees in parallel.
for en, fr in zip(english_root, french_root):
   assert en.tag == fr.tag # check for the same structure
   if en.tag == 'id':
       assert en.text == fr.text # check for the same id

   elif en.tag == 'string':
       if fr.text is None:
           fr.text = en.text
           print en.text      # displaying what was replaced

etree.dump(french_tree)

对于更复杂的文件结构,可以通过遍历树的所有元素来替换通过节点的直接子节点的循环。如果文件的结构完全相同,则以下代码将起作用:

import xml.etree.ElementTree as etree

english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')

for en, fr in zip(english_tree.iter(), french_tree.iter()):
   assert en.tag == fr.tag        # check if the structure is the same
   if en.tag == 'id':
       assert en.text == fr.text  # identification must be the same
   elif en.tag == 'string':
       if fr.text is None:
           fr.text = en.text
           print en.text          # display the inserted text

# Write the result to the output file.
with open('fr2.xml', 'w') as fout:
    fout.write(etree.tostring(french_tree.getroot()))

但是,它仅适用于两个文件具有完全相同结构的情况。让我们遵循手动完成任务时将使用的算法。首先,我们需要找到空的法语翻译。然后它应该由具有相同标识的 GH 元素的英文翻译替换。在搜索元素时使用 XPath 表达式的子集:

import xml.etree.ElementTree as etree

def find_translation(tree, id_):
    # Search fot the GH element with the given identification, and return
    # its translation if found. Otherwise None is returned implicitly.
    for gh in tree.iter('GH'):
       id_elem = gh.find('./id')
       if id_ == id_elem.text:
           # The related GH element found.
           # Find metadata entry, extract the translation.
           # Warning! This is simplification for the fixed position 
           # of the Translation entry.
           me = gh.find('./metadata/entry')
           assert len(me) == 2     # metadata/entry has two elements
           cl1 = me[0]
           assert cl1.text == 'Translation'
           cl2 = me[1]

           return cl2.text


# Body of the program. --------------------------------------------------

english_tree = etree.parse('en.xml')
french_tree = etree.parse('fr.xml')

for gh in french_tree.iter('GH'): # iterate through the GH elements only 
   # Get the identification of the GH section
   id_elem = gh.find('./id')      
   id_ = id_elem.text

   # Find and check the metadata entry, extract the French translation.
   # Warning! This is simplification for the fixed position of the Translation 
   # entry.
   me = gh.find('./metadata/entry')
   assert len(me) == 2     # metadata/entry has two elements
   cl1 = me[0]
   assert cl1.text == 'Translation'
   cl2 = me[1]
   fr_translation = cl2.text

   # If the French translation is empty, put there the English translation
   # from the related element.
   if cl2.text is None:
       cl2.text = find_translation(english_tree, id_)


with open('fr2.xml', 'w') as fout:
   fout.write(etree.tostring(french_tree.getroot()).decode('utf-8'))
于 2012-07-17T07:58:55.297 回答