第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Python 中解析嵌套且復雜的 XML

在 Python 中解析嵌套且復雜的 XML

尚方寶劍之說 2023-10-26 10:34:06
我正在嘗試解析相當復雜的 xml 文件并將其內容存儲在數(shù)據(jù)框中。我嘗試了 xml.etree.ElementTree 并且設法檢索了一些元素,但我以某種方式多次檢索了它,就好像有更多對象一樣。我正在嘗試提取以下內容:category, created, last_updated, accession type, name type identifier, name type synonym as a list<cellosaurus><cell-line category="Hybridoma" created="2012-06-06" last_updated="2020-03-12" entry_version="6">  <accession-list>    <accession type="primary">CVCL_B375</accession>  </accession-list>  <name-list>    <name type="identifier">#490</name>    <name type="synonym">490</name>    <name type="synonym">Mab 7</name>    <name type="synonym">Mab7</name>  </name-list>  <comment-list>    <comment category="Monoclonal antibody target"> Cronartium ribicola antigens </comment>    <comment category="Monoclonal antibody isotype"> IgM, kappa </comment>  </comment-list>  <species-list>    <cv-term terminology="NCBI-Taxonomy" accession="10090">Mus musculus</cv-term>  </species-list>  <derived-from>    <cv-term terminology="Cellosaurus" accession="CVCL_4032">P3X63Ag8.653</cv-term>  </derived-from>  <reference-list>    <reference resource-internal-ref="Patent=US5616470"/>  </reference-list>  <xref-list>    <xref database="CLO" category="Ontologies" accession="CLO_0001018">      <url><![CDATA[https://www.ebi.ac.uk/ols/ontologies/clo/terms?iri=http://purl.obolibrary.org/obo/CLO_0001018]]></url>    </xref>    <xref database="ATCC" category="Cell line collections" accession="HB-12029">      <url><![CDATA[https://www.atcc.org/Products/All/HB-12029.aspx]]></url>    </xref>    <xref database="Wikidata" category="Other" accession="Q54422073">      <url><![CDATA[https://www.wikidata.org/wiki/Q54422073]]></url>    </xref>  </xref-list></cell-line></cellosaurus>
查看完整描述

3 回答

?
藍山帝景

TA貢獻1843條經(jīng)驗 獲得超7個贊

鑒于在某些情況下您希望解析標簽屬性,而在其他情況下您希望解析 tag_values,您的問題有點不清楚。

我的理解如下。您需要以下值:

  1. 標簽cell-line的屬性類別的值。

  2. 標簽cell-line創(chuàng)建的屬性值。

  3. 標簽cell-line的屬性last_updated的值。

  4. 標簽加入的屬性類型的值。

  5. 與具有屬性標識符的標簽名稱相對應的文本。

  6. 與帶有屬性synonym 的標簽名稱相對應的文本。

這些值可以使用模塊 xml.etree.Etree 從 xml 文件中提取。特別是,請注意使用Element 類的findall和iter方法。

假設 xml 位于名為input.xml的文件中,則以下代碼片段應該可以解決問題。

import xml.etree.ElementTree as et



def main():

? ? tree = et.parse('cellosaurus.xml')

? ? root = tree.getroot()


? ? results = []

? ? for element in root.findall('.//cell-line'):

? ? ? ? key_values = {}

? ? ? ? for key in ['category', 'created', 'last_updated']:

? ? ? ? ? ? key_values[key] = element.attrib[key]

? ? ? ? for child in element.iter():

? ? ? ? ? ? if child.tag == 'accession':

? ? ? ? ? ? ? ? key_values['accession type'] = child.attrib['type']

? ? ? ? ? ? elif child.tag == 'name' and child.attrib['type'] == 'identifier':

? ? ? ? ? ? ? ? key_values['name type identifier'] = child.text

? ? ? ? ? ? elif child.tag == 'name' and child.attrib['type'] == 'synonym':

? ? ? ? ? ? ? ? key_values['name type synonym'] = child.text

? ? ? ? results.append([

? ? ? ? ? ? ? ? # Using the get method of the dict object in case any particular

? ? ? ? ? ? ? ? # entry does not have all the required attributes.

? ? ? ? ? ? ? ? ?key_values.get('category'? ? ? ? ? ? , None)

? ? ? ? ? ? ? ? ,key_values.get('created'? ? ? ? ? ? ?, None)

? ? ? ? ? ? ? ? ,key_values.get('last_updated'? ? ? ? , None)

? ? ? ? ? ? ? ? ,key_values.get('accession type'? ? ? , None)

? ? ? ? ? ? ? ? ,key_values.get('name type identifier', None)

? ? ? ? ? ? ? ? ,key_values.get('name type synonym'? ?, None)

? ? ? ? ? ? ? ? ])


? ? print(results)



if __name__ == '__main__':

? ? main()


查看完整回答
反對 回復 2023-10-26
?
狐的傳說

TA貢獻1804條經(jīng)驗 獲得超3個贊

恕我直言,解析 xml 的最簡單方法是使用 lxml。


from lxml import etree

data = """[your xml above]"""

doc = etree.XML(data)

for att in doc.xpath('//cell-line'):

    print(att.attrib['category'])

    print(att.attrib['last_updated'])

    print(att.xpath('.//accession/@type')[0])

    print(att.xpath('.//name[@type="identifier"]/text()')[0])

    print(att.xpath('.//name[@type="synonym"]/text()'))

輸出:


Hybridoma

2020-03-12

primary

#490

['490', 'Mab 7', 'Mab7']

然后,您可以將輸出分配給變量、附加到列表等。


查看完整回答
反對 回復 2023-10-26
?
呼喚遠方

TA貢獻1856條經(jīng)驗 獲得超11個贊

另一種方法。最近比較了幾個XML解析庫,發(fā)現(xiàn)這個很好用。我推薦它。


from simplified_scrapy import SimplifiedDoc, utils


xml = '''your xml above'''

# xml = utils.getFileContent('your file name.xml')


results = []

doc = SimplifiedDoc(xml)

for ele in doc.selects('cell-line'):

  key_values = {}

  for k in ele:

    if k not in ['tag','html']:

      key_values[k]=ele[k]

  key_values['name type identifier'] = ele.select('name@type="identifier">text()')

  key_values['name type synonym'] = ele.selects('name@type="synonym">text()')

  results.append(key_values)

print (results)

結果:


[{'category': 'Hybridoma', 'created': '2012-06-06', 'last_updated': '2020-03-12', 'entry_version': '6', 'name type identifier': '#490', 'name type synonym': ['490', 'Mab 7', 'Mab7']}]



查看完整回答
反對 回復 2023-10-26
  • 3 回答
  • 0 關注
  • 221 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號