2016-01-14 26 views
1
我在python初學者之間

。我正在努力解決下面解釋的問題。我分享不完整的Python腳本也不適用於這個問題。如果得到我的腳本的支持或指導,我將不勝感激。提取物,如果彭定康發現

文件看起來是這樣的:

<Iteration> 
    <Iteration_hit>Elememt1 Element1 
    abc1 hit 1 
    . 
    . 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt2 Element2 
    abc2 hit 1 
    . 
    . 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt3 Element3 
    abc3 hit 1 
    . 
    . 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt4 Element4 
    abc4 hit 1 
    . 
    . 
</Iteration> 

我從<Iteration>需要</Iteration>的元素列表匹配,這意味着元素2和元素4輸出文件應該是這樣的:

<Iteration> 
    <Iteration_hit>Elememt2 Element2 
    abc2 hit 1 
    . 
    . 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt4 Element4 
    abc4 hit 1 
    . 
    . 
</Iteration> 

腳本

#!/usr/bin/python 
x = raw_input("Enter your xml file name: ") 
xml = open(x) 
l = raw_input("Enter your list file name: ") 
lst = open(l) 
Id = list() 
ylist = list() 
import re 
for line in lst: 
     stuff=line.rstrip() 
     stuff.split() 
     Id.append(stuff) 
for ele in Id: 
     for line1 in xml: 
       if line1.startswith(" <Iteration_hit>"): 
         y = line1.split() 
#      print y[1] 
         if y[1] == ele: break 
+1

你知道有ar e庫讀取/寫入xml文件,對吧? – tglaria

+0

不要使用正則表達式解析XML。 Python爲此提供了一個'xml'包。 –

+0

謝謝...我不知道...我會嘗試使用這些庫 – kashiff007

回答

0

不建議使用REG前解析XML - 你應該使用一個庫如lxml,您可以安裝使用pip install lxml

content = ''' 
<root> 
<Iteration> 
    <Iteration_hit>Elememt1 Element1 
    abc1 hit 1 
    </Iteration_hit> 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt2 Element2 
    abc2 hit 1 
    </Iteration_hit> 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt3 Element3 
    abc3 hit 1 
    </Iteration_hit> 
</Iteration> 
<Iteration> 
    <Iteration_hit>Elememt4 Element4 
    abc4 hit 1 
    </Iteration_hit> 
</Iteration> 
</root> 
''' 

from lxml import etree 

tree = etree.XML(content) 
target_elements = tree.xpath('//Iteration_hit[contains(., "Element2") or contains(., "Element4")]') 

for element in target_elements: 
    print(etree.tostring(element)) 

輸出

<Iteration_hit>Elememt2 Element2 
    abc2 hit 1 
    </Iteration_hit> 

<Iteration_hit>Elememt4 Element4 
    abc4 hit 1 
    </Iteration_hit> 
+0

謝謝....它的工作原理 – kashiff007

+0

樂於幫忙,歡迎來到Stack Overflow。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 – gtlambert

0

這裏:然後,你可以使用lxmlXPath如下(我已經採取了關閉在XML的<Iteration_hit>標籤的自由)選擇適當的元素輸出是通過Python進行xml解析所需的完整腳本

#!/usr/bin/python 
from lxml import etree 

with open('input.xml', 'r') as myfile: 
    content=myfile.read().replace('\n', '\n') 


lst = open('ID.list') 
Id = list() 
for line in lst: 
    stuff=line.rstrip() 
    stuff.split() 
    Id.append(stuff) 
for ele in Id: 
    tree = etree.XML(content) 
    target_elements = tree.xpath('//Iteration[contains(., ele)]') 

for element in target_elements: 
    print(etree.tostring(element))