编辑多个XML文档的属性

时间:2014-09-18 20:12:54

标签: python xml xml-parsing ipython elementtree

这是我正在使用的一个XML文档:

<?xml version="1.0"?>
<document DOCID="501.conll.txt">
<span type="sentence">
  <extent>
    <charseq START="0" END="30">ATRIA SEES H2 RESULT UP ON H1 .</charseq>
  </extent>
</span><span type="sentence">
  <extent>
    <charseq START="205" END="310">" The result of the second year-half is expected to improve on     the early part of the year , " Atria said .</charseq>

我循环浏览一组XML文档以检索以空格开头的所有句子。我可以毫不费力地捕获所有错误(前导空格):

>>> import re, os, sys
>>> import xml.etree.ElementTree as etree
>>> sentences = {}

>>> xmlAddresses = getListOfFilesInFolders(['XMLFiles'],ending=u'.xml') # my function to grab all XML files

>>> for docAddr in xmlAddresses:
>>>    parser = etree.XMLParser(encoding=u'utf-8') 
>>>    tree = etree.parse(docAddr, parser=parser) 
>>>    sentences = getTokenTextFeature(docAddr,tree,sentences) 

>>> rgxLeadingSpace = re.compile('^\"? .')
>>> for sent in sentences.keys():
>>>    text = sentences[sent]['sentence']
>>>    if rgxLeadingSpace.findall(text):    
>>>        print text                        # the second sentence is from the above XML doc

" It rallied on ideas the market was oversold , " a trader said . 

" The result of the second year-half is expected to improve on the early part of the year , " Atria said .

" The head of state 's holiday has only just begun , " the agency quoted Sergei Yastrzhembsky as saying , adding that the president was currently in a Kremlin residence near Moscow . 

我需要做的是,找到错误后,遍历包含这些错误的所有XML文件并调整其START属性。例如,这是上述XML文档中包含前导空格的句子:

<charseq START="205" END="310">" The result of the second year-half is expected to improve on     the early part of the year , " Atria said .</charseq>

它应该是这样的:

<charseq START="207" END="310">The result of the second year-half is expected to improve on     the early part of the year , " Atria said .</charseq>

我想我提供了所有必要的代码。 如果有人可以帮助我,我将创建一百万个StackOverflow帐户,并为您提供一百万次! :) 谢谢!

2 个答案:

答案 0 :(得分:1)

我将使用的方法是不提取,然后在你正在进行的单独数组中搜索匹配的句子,而是在遍历dom的节点时检查每个句子元素与你的模式。这样,当您找到一个时,您可以使用您直接访问的元素对象并修改其START属性,然后将修改后的dom写入新的(或替换的)XML文件。

答案 1 :(得分:1)

我不知道getTokenTextFeature的作用,但这是一个以您要求的方式修改XML的程序。

xml='''<?xml version="1.0"?>
<document DOCID="501.conll.txt">
<span type="sentence">
  <extent>
    <charseq START="0" END="30">ATRIA SEES H2 RESULT UP ON H1 .</charseq>
  </extent>
</span><span type="sentence">
  <extent>
    <charseq START="205" END="310">" The result of the second year-half is expected to improve on     the early part of the year , " Atria said .</charseq>
</extent></span></document>
'''

import re
import xml.etree.ElementTree as etree

root = etree.XML(xml)
for charseq in root.findall(".//span[@type='sentence']/extent/charseq[@START]"):
  match = re.match('^("? +)(.*)', charseq.text)
  if match:
    space,text = match.groups()
    charseq.set('START', str(int(charseq.get('START')) + len(space)))
    charseq.text = text
print etree.tostring(root)