gpt4 book ai didi

python-3.x - 如何访问 child 的xml文本?

转载 作者:行者123 更新时间:2023-12-04 10:10:13 26 4
gpt4 key购买 nike

我有以下 xml 文件(取自 here :

<BioSampleSet>
<BioSample submission_date="2011-12-01T13:31:02.367" last_update="2014-11-08T01:40:24.717" publication_date="2012-02-16T10:49:52.970" access="public" id="761094" accession="SAMN00761094">
<Ids>
</Ids>
<Package display_name="Generic">Generic.1.0</Package>
<Attributes>
<Attribute attribute_name="Individual">PK314</Attribute>
<Attribute attribute_name="condition">healthy</Attribute>
<Attribute attribute_name="BioSampleModel">Generic</Attribute>
</Attributes>
<Status status="live" when="2014-11-08T00:27:24"/>
</BioSample>
</BioSampleSet>

我需要访问属性旁边的文本 attribute_name child 的 Attributes .
我设法访问了 attribute_name 的值.:
from Bio import Entrez,SeqIO
Entrez.email = '#'
import xml.etree.ElementTree as ET

handle = Entrez.efetch(db="biosample", id="SAMN00761094", retmode="xml", rettype="full")
tree = ET.parse(handle)
for attr in root[0].iter('Attribute'):
name = attr.get('attribute_name')
print(name)

这打印:
Individual
condition
BioSampleModel

我如何创建 dict attribute_name 的值和它旁边的文字?

我想要的输出是
attributes = {'Individual': PK314, 'condition': healthy, 'BioSampleModel': Generic}

最佳答案

严格根据问题中的 xml 示例,尝试以下几行:

bio = """[your xml sample]"""
doc = ET.fromstring(bio)
attributes = {}
for item in doc.findall('.//Attributes//Attribute'):
attributes[item.attrib['attribute_name']]=item.text
attributes

输出:
{'Individual': 'PK314', 'condition': 'healthy', 'BioSampleModel': 'Generic'}

关于python-3.x - 如何访问 child 的xml文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61364551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com