【问题标题】:extracting specific data from a xml file从 xml 文件中提取特定数据
【发布时间】:2014-02-02 16:58:58
【问题描述】:

我有一个这样的 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>

我想得到如下输出。

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

实现这一目标的简单方法是什么?这是我第一次处理xml文件。您的宝贵建议将不胜感激!

【问题讨论】:

  • 确保 XML 格式正确,然后使用任何 XML 解析器。
  • 为什么不希望输出列号。 2 代表pr_id=01?

标签: python xml perl awk


【解决方案1】:

在 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

【讨论】:

  • 感谢您的回答。我没有得到我想要的输出。我得到了这样的输出 pr_id uniprot old_start old_end 01 O11482 我使用 ubuntu12.04 并使用命令 sudo dpkg -i gawk_4.0.1+dfsg-2_amd64.deb 安装了 gawk。请帮助我
  • @user3194459 我也在使用 Ubuntu 12.04。但我使用的是 Gnu Awk 4.1 版(不是 4.0.1 版),也许你可以试试 4.1 版?
【解决方案2】:

取决于 XML 的大小,但是为什么不使用 python 的 minidom 来处理最大 30 兆的 XML 或 SAX,如果你超过了这个。

如果您只需要一次,即使 Excel 也可以解决问题。

然而,这一切都依赖于格式良好的 XML(将其拖入浏览器,或使用某种 XML 工具进行验证)。您发布的 XML 似乎有点不对劲。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多