Я думаю, что понял, хотя это заняло некоторое время.Чтобы сделать это интересным упражнением, я внес некоторые изменения.
Во-первых, код xml в вашем вопросе недействителен; Вы можете проверить это здесь, например .
Итак, сначала я исправил xml.Кроме того, я превратил его в набор PubmedArticleSet, чтобы в нем было 2 статьи: первая статья содержит 3 автора, а вторая - две (очевидно, фиктивная информация), просто чтобы гарантировать, что код захватит их все.Чтобы сделать его несколько проще, я удалил некоторую не относящуюся к этому упражнению информацию, такую как «Принадлежность».
Итак, вот что нам остается.Сначала модифицируем xml:
source = """
<PubmedArticleSet>
<PubmedArticle>
<MedlineCitation Status="MEDLINE" Owner="NLM">
<PMID Version="1">2844048</PMID>
<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>Guarner</LastName>
<ForeName>J</ForeName>
<Initials>J</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Cohen</LastName>
<ForeName>C</ForeName>
<Initials>C</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Mushi</LastName>
<ForeName>E</ForeName>
<Initials>F</Initials>
</Author>
</AuthorList>
</MedlineCitation>
</PubmedArticle>
<PubmedArticle>
<MedlineCitation Status="MEDLINE" Owner="NLM">
<PMID Version="1">123456</PMID>
<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>Smith</LastName>
<ForeName>C</ForeName>
<Initials>C</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Jones</LastName>
<ForeName>E</ForeName>
<Initials>F</Initials>
</Author>
</AuthorList>
</MedlineCitation>
</PubmedArticle>
"""
Далее импортируем то, что нужно импортировать:
from lxml import etree
import pandas as pd
Далее код:
doc = etree.fromstring(source)
art_loc = '..//*/PubmedArticle' #this is the path to all the articles
#count the number of articles in the article set - that number is a float has to be converted to integer before use:
num_arts = int(doc.xpath(f'count({art_loc})')) # or could use len(doc.xpath(f'({art_loc})'))
grand_inf = [] #this list will hold the accumulated information at the end
for art in range(1,num_arts+1): #can't do range(num_arts) because of the different ways python and Pubmed count
loc_path = (f'{art_loc}[{art}]/*/') #locate the path to each article
#grab the article id:
id_path = loc_path+'PMID'
pmid = doc.xpath(id_path)[0].text
art_inf = [] #this list holds the information for each article
art_inf.append(pmid)
art_path = loc_path+'/Author' #locate the path to the author group
#determine the number of authors for this article; again, it's a float which needs to converted to integer
num_auths = int(doc.xpath(f'count({art_path})')) #again: could use len(doc.xpath(f'({art_path})'))
auth_inf = [] #this will hold the full name of each of the authors
for auth in range(1,num_auths+1):
auth_path = (f'{art_path}[{auth}]') #locate the path to each author
LastName = doc.xpath((f'{auth_path}/LastName'))[0].text
FirstName = doc.xpath((f'{auth_path}/ForeName'))[0].text
Middle = doc.xpath((f'{auth_path}/Initials'))[0].text
full_name = LastName+' '+FirstName+' '+Middle
auth_inf.append(full_name)
art_inf.append(auth_inf)
grand_inf.append(art_inf)
Наконец, загрузите эту информацию в фрейм данных:
df=pd.DataFrame(grand_inf,columns=['PMID','Author(s)'])
df
Вывод:
PMID Author(s)
0 2844048 [Guarner J J, Cohen C C, Mushi E F]
1 123456 [Smith C C, Jones E F]
И теперь мы можем отдохнуть ...