3 回答

TA貢獻1843條經(jīng)驗 獲得超7個贊
鑒于在某些情況下您希望解析標簽屬性,而在其他情況下您希望解析 tag_values,您的問題有點不清楚。
我的理解如下。您需要以下值:
標簽cell-line的屬性類別的值。
標簽cell-line創(chuàng)建的屬性值。
標簽cell-line的屬性last_updated的值。
標簽加入的屬性類型的值。
與具有屬性標識符的標簽名稱相對應的文本。
與帶有屬性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()

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']
然后,您可以將輸出分配給變量、附加到列表等。

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']}]
添加回答
舉報