Как я могу написать это более простым способом? - PullRequest
1 голос
/ 17 февраля 2020

У меня есть несколько строк XML, из которых мне нужно разобрать и извлечь названия видов для списка реакций и продуктов, поэтому я пробовал использовать следующие строки, но мне интересно, есть ли способ, которым я могу это сделать более четко

XML:

<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="data" level="2" version="1">
  <model id="E" name="core_model">
    <notes>
    <listOfUnitDefinitions>
    <listOfCompartments>
    <listOfSpecies>
    <listOfReactions>
      <reaction id="ID_1" name="name_1">
        <notes>
        <listOfReactants>
          <speciesReference species="react_1_1"/>
          <speciesReference species="react_2_1"/>
          <speciesReference species="react_3_1"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="produ_1_1"/>
          <speciesReference species="produ_2_1"/>
          <speciesReference species="produ_3_1"/>
        </listOfProducts>
        <kineticLaw>
      </reaction>
      <reaction id="ID_2" name="name_2">
        <notes>
        <listOfReactants>
          <speciesReference species="react_1_2"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="produ_1_2"/>
        </listOfProducts>
        <kineticLaw>
      </reaction>
      <reaction id="ID_3" name="name_3">
        <notes>
        <listOfReactants>
          <speciesReference species="react_1_3"/>
          <speciesReference species="react_2_3"/>
        </listOfReactants>
        <listOfProducts>
          <speciesReference species="produ_1_3"/>
          <speciesReference species="produ_2_3"/>
        </listOfProducts>
        <kineticLaw>
      </reaction>
    </listOfReactions>
  </model>
</sbml>

Python:

import xml.etree.ElementTree as et
tree = et.parse('example.xml')
root = tree.getroot()
child = root[0]

for x in child[4]: #to get the list of REACTIONS ids and names
    print (x.get('id'),':',x.get('name'))

for h in range(2): #gives back the list of species for reactants and products
    for i in range(2):
        for x in child[4][h][i+1]:
            print(x.get('species'))

Отпечатки:

react_1_1
react_2_1
react_3_1
produ_1_1
produ_2_1
produ_3_1
react_1_2
produ_1_2

Желаемый вывод

ID_1
Reactants
react_1_1
react_2_1
react_3_1
Products
produ_1_1
produ_2_1
produ_3_1

ID_2
Reactions
react_1_2
Products
produ_1_2
.
.
.

с помощью кода python я могу анализировать и извлекать названия видов, но на выходе получается список без различия между реакциями и продуктами, я также пытался использовать element.iter (), но безуспешно

...