【问题标题】:Converting XML file into CSV将 XML 文件转换为 CSV
【发布时间】:2014-11-22 14:25:18
【问题描述】:

我有一个XML 文件,如下所示:

<Organism>
 <Name>Bacillus halodurans C-125</Name>
  <Enzyme>M.BhaII</Enzyme>
   <Motif>GGCC</Motif>
  <Enzyme>M1.BhaI</Enzyme>
   <Motif>GCATC</Motif>
  <Enzyme>M2.BhaI</Enzyme>
   <Motif>GCATC</Motif>
</Organism>
<Organism>
 <Name>Bacteroides eggerthii 1_2_48FAA</Name>
</Organism>

我正在尝试将其写入CSV 文件,如下所示:

Bacillus halodurans, GGCC
Bacillus halodurans, GCATC
Bacillus halodurans, GCATC
Bacteriodes, 

我解决这个问题的方法是创建一个元组列表,其中包含organism name 和motif。我使用ElementTree 模块尝试了这个:

import xml.etree.ElementTree as ET

tree = ET.parse('file.xml')
rebase = tree.getroot()

list = []

for organisms in rebase.findall('Organism'):
        name = organisms.find('Name').text
        for each_organism in organisms.findall('Motif'):
            try:
                motif = organisms.find('Motif').text
                print name, motif
            except AttributeError:
                print name

但是我得到的输出是这样的:

Bacillus halodurans, GGCC
Bacillus halodurans, GGCC
Bacillus halodurans, GGCC

仅记录第一个 motif。这是我第一次使用ElementTree,所以有点混乱。任何帮助将不胜感激。

我在写入 CSV 文件时不需要帮助。

【问题讨论】:

    标签: python xml csv


    【解决方案1】:

    您唯一需要修复的就是更换:

    motif = organisms.find('Motif').text
    

    与:

    motif = each_organism.text
    

    您已经在Organism 中的Motif 节点中进行迭代。 each_organism 循环变量的值是 Motif 标记。


    我还会更改变量名称以避免混淆。此外,我认为在 Motif 标签的循环中不需要 try/except。如果可能缺少name 标签,您可以按照“请求原谅,而不是许可”的方法来捕获错误:

    for organism in rebase.findall('Organism'):
        try:
            name = organism.find('Name').text
        except AttributeError:
            continue
    
        for motif in organism.findall('Motif'):
            motif = motif.text
            print name, motif
    

    【讨论】:

    • 像魅力一样工作。但是在文件中的某些点,organism 标签下只有一个name 标签。在这种情况下,我在name = organisms.find('Name').text 行收到AttributeError: 'NoneType' object has no attribute 'text' 的错误消息
    • @Beginner 好的,我已经更新了答案。据我了解,您想跳过没有名称的Organisms - 为此我在except 块中使用了continue。谢谢。
    猜你喜欢
    • 2011-03-05
    • 2015-10-28
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多