2015-11-16 89 views
0

在下面的函數中,我想將嵌入式字典的項目顯示爲XML樹並將其打印到文件中。將Python打印爲XML文件

def printToFile(self): 
     from lxml import etree as ET 
     for k,v in self.wordCount.items(): 
      root = ET.Element(k) 
      tree = ET.ElementTree(root) 
      for k1,v1 in v.items(): 
       DocID = ET.SubElement(root, 'DocID') 
       DocID.text = str(k1) 
       Occurences = ET.SubElement(root, 'Occurences') 
       Occurences.text = str(v1) 
      print ET.tostring(root, pretty_print=True, xml_declaration=False) 
      tree.write('output.xml', pretty_print=True, xml_declaration=False) 

當我運行代碼,所有的項目都顯示在控制檯屏幕,但問題是,它只能打印文件中的最後一項。

在控制檯中,我得到這個:

<weather> 
    <DocID>1</DocID> 
    <Occurences>1</Occurences> 
</weather> 

<london> 
    <DocID>1</DocID> 
    <Occurences>1</Occurences> 
    <DocID>2</DocID> 
    <Occurences>2</Occurences> 
    <DocID>3</DocID> 
    <Occurences>1</Occurences> 
</london> 

<expens> 
    <DocID>2</DocID> 
    <Occurences>1</Occurences> 
</expens> 

<nice> 
    <DocID>3</DocID> 
    <Occurences>1</Occurences> 
</nice> 

但是當我打開該文件,我只得到了這一點:

<nice> 
    <DocID>3</DocID> 
    <Occurences>1</Occurences> 
</nice> 

有人可以幫助我解決這個問題。由於

+1

你每次循環再造的樹。 –

+0

@MorganThrapp它沒有工作 – Nasser

+3

每次循環訪問for循環時,都會覆蓋output.xml文件。相反,你應該追加到文件http://stackoverflow.com/questions/4706499/how-do-you-append-to-a-file-in-python – Woodsy

回答

0

基於先前的評論,我改變了我的函數如下,它的工作:

def printToFile(self): 
     from lxml import etree as ET 
     with open('output.xml','a') as file: 
      for k,v in self.wordCount.items(): 
       root = ET.Element(k) 
       for k1,v1 in v.items(): 
        DocID = ET.SubElement(root, 'DocID') 
        DocID.text = str(k1) 
        Occurences = ET.SubElement(root, 'Occurences') 
        Occurences.text = str(v1) 
       //print ET.tostring(root, pretty_print=True, xml_declaration=False) 
       file.write(ET.tostring(root, pretty_print=True, xml_declaration=False))