TypeError:列表索引必须是整数,而不是带有xmltodict的str:

2024-06-29 01:12:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个XML文件:

<?xml version="1.0"?>
<toolbox tool_path="/galaxy/main/shed_tools">
<section id="snpeff" name="snpEff" version="">
  <tool file="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/c052639fa666/snpeff/snpEff_2_1a/snpEff_2_1a/galaxy/snpSift_filter.xml" guid="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpSift_filter/1.0">
      <tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
        <repository_name>snpeff</repository_name>
        <repository_owner>pcingola</repository_owner>
        <installed_changeset_revision>c052639fa666</installed_changeset_revision>
        <id>toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpSift_filter/1.0</id>
        <version>1.0</version>
    </tool>
    <tool file="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/c052639fa666/snpeff/snpEff_2_1a/snpEff_2_1a/galaxy/snpEff.xml" guid="toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpEff/1.0">
      <tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
        <repository_name>snpeff</repository_name>
        <repository_owner>pcingola</repository_owner>
        <installed_changeset_revision>c052639fa666</installed_changeset_revision>
        <id>toolshed.g2.bx.psu.edu/repos/pcingola/snpeff/snpEff/1.0</id>
        <version>1.0</version>
    </tool>
    <tool file="toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/22c8c4f8d11c/check_snpeff_candidates/checkSnpEffCandidates.xml" guid="toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/check_snpeff_candidates/1.0.0">
      <tool_shed>toolshed.g2.bx.psu.edu</tool_shed>
        <repository_name>check_snpeff_candidates</repository_name>
        <repository_owner>gregory-minevich</repository_owner>
        <installed_changeset_revision>22c8c4f8d11c</installed_changeset_revision>
        <id>toolshed.g2.bx.psu.edu/repos/gregory-minevich/check_snpeff_candidates/check_snpeff_candidates/1.0.0</id>
        <version>1.0.0</version>
    </tool>
</section>
...

我尝试用以下方式解析上述文件:

^{pr2}$

但是,我得到了以下错误:

Traceback (most recent call last):
  File "importTools2Galaxy.py", line 15, in <module>
    tools_section = doc['toolbox']['section']['@name']
TypeError: list indices must be integers, not str

我做错什么了?在


Tags: nameidversionrepositorytoolrepospsuedu
2条回答

您的XML有许多section元素,您应该执行以下操作

tools_section = doc['toolbox']['section'][0]

其中0是要读取的节的索引。如果索引不是固定的,您可以像for section in doc['toolbox']['section']: ...一样对其进行迭代,并在内容与您的条件匹配的部分停止。。。或者对每个部分做些什么。在

这是因为doc['toolbox']['section']返回了一个list的节,因此您需要迭代每个节来获得@name值。您可能需要检查@name是否在给定的部分中。为此,您可能需要使用.get而不是['@name']

with open('tests/shed_tool_conf.xml') as fd:
        doc = xmltodict.parse(fd.read())
        for section in doc['toolbox']['section']:
            tools_section = section.get('@name')
        print tools_section

相关问题 更多 >