2014-01-14 52 views
0

具體的數據我有這樣提取XML文件

<pr_id>01</pr_id> 
    <uniprot>O11482</uniprot> 
    <uniprot>O96642</uniprot> 
    <uniprot>Q67845</uniprot> 
    <column> 
     <column_id>1</column_id> 
     column_start>300</column_start> 
     <column_end>334</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 
    </column> 
    <column> 
     <column_id>2</column_id> 
     <column_start>335</column_start> 
     <column_end>337</column_end> 
     <old_new>new</old_new> 
     <comment></comment> 
     <pr_id>02</pr_id> 
     <uniprot>P4455</uniprot> 
     <uniprot>89WER8</uniprot> 
     <uniprot>Q12845</uniprot> 
      <column> 
     <column_id>1</column_id> 
     <column_start>12</column_start> 
     <column_end>34</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 
     </column> 
     <column> 
     <column_id>2</column_id> 
     <column_start>35</column_start> 
     <column_end>37</column_end> 
     <old_new>old</old_new> 
     <comment></comment> 

我想獲得如下輸出XML文件。

pr_id uniprot old_start old_end 
01  O11482 300   334 
02  P4455 12   34 
02  P4455 35   37 

實現此目的的簡單方法是什麼?這是我第一次處理xml文件。您的寶貴意見將不勝感激!

+2

確保XML的簡潔(wellformed)然後使用任何XML解析器。 – thefourtheye

+2

可能的重複:[如何在python中解析XML?](http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – valverij

+0

爲什麼你不想輸出列沒有。 2爲'pr_id = 01'? –

回答

2

在了GNU AWK版本4,您可以使用split()功能:

gawk -f a.awk file.xml 

其中a.awk是:

BEGIN {RS="^$"} 
{ 
    n=split($0,a,/<\/?(uniprot|pr_id|column_start|column_end|old_new)>/,s) 
    for (i=1; i<=n-1;i+=2) { 
     if (s[i]=="<pr_id>") {pp=a[i+1]; up=0} 
     if (s[i]=="<uniprot>" && up==0) {uu=a[i+1];up=1} 
     if (s[i]=="<column_start>") ss=a[i+1] 
     if (s[i]=="<column_end>") ee=a[i+1] 
     if (s[i]=="<old_new>" && a[i+1]=="old") { 
      p[++k]=pp 
      u[k]=uu 
      s[k]=ss 
      e[k]=ee 
     } 
    } 
} 
END { 
    fmt="%5s%10s%10s%10s\n" 
    printf fmt, "pr_id", "uniprot", "old_start", "old_end" 
    for (i=1; i<=k; i++) 
     printf fmt,p[i],u[i],s[i],e[i] 
} 

輸出:

pr_id uniprot old_start old_end 
    01 O11482  300  334 
    02  P4455  12  34 
    02  P4455  35  37 
+0

感謝您的回答。我沒有得到我想要的輸出。我得到了這樣的輸出pr_id uniprot old_start old_end 01 O11482我使用ubuntu12.04和剛安裝的gawk使用命令sudo dpkg -i gawk_4.0.1 + dfsg-2_amd64.deb。請幫助我 – user3194459

+0

@ user3194459我也在使用Ubuntu 12.04。但我使用Gnu Awk版本4.1(不是版本4.0.1),也許你可以試試版本4.1? –

+0

非常感謝! – user3194459

1

取決於XML的大小,但爲什麼不使用python的minidom獲得大小爲30 megs或SAX的XML(如果您高於該值)。

即使Excel可能會訣竅,如果你只需要它一次。

但是,所有這些都依賴於格式良好的XML(將其拖入瀏覽器或使用某種XML工具進行驗證)。你發佈的XML似乎有點偏離。