【发布时间】: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 文件时不需要帮助。
【问题讨论】: