XML ElementTree - 索引标记

时间:2017-03-29 14:07:51

标签: python xml elementtree xml.etree

我有一个XML文件:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I&apos;ve been to this restaurant over a dozen times with no complaints to date.</text>
</sentence>

使用XML ElementTree,我想插入一个具有属性<Opinion>的标记category=。假设我有一个字符列表list = ['a', 'b', 'c'],是否可以逐步将它们与每个文本对齐,所以我有:

<sentence id="en_BlueRibbonSushi_478218345:2">
   <text>It has great sushi and even better service.</text>
   <Opinion category='a' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:3">
   <text>The entire staff was extremely accomodating and tended to my every need.</text>
   <Opinion category='b' />
</sentence>
<sentence id="en_BlueRibbonSushi_478218345:4">
   <text>I&apos;ve been to this restaurant over a dozen times with no complaints to date.</text>
   <Opinion category='c' />
</sentence>

我知道我可以使用句子id属性,但这需要对我的代码进行大量重组。基本上,我希望能够将每个句子索引编入索引以与我的列表索引保持一致。

1 个答案:

答案 0 :(得分:4)

您可以使用SubElement工厂函数向树中添加元素。 假设您的XML数据位于名为data的变量中,这会将元素添加到文档树中:

import xml.etree.ElementTree as ET
tree = ET.XML(data)
for elem, category in zip(tree.findall('sentence'), ['a', 'b', 'c']):
    Opinion  = ET.SubElement(elem, 'Opinion')
    Opinion.set('category', category)

ET.dump(tree)  # prints the tree; tree.write('output.xml') is another option