Something like this will work, it did just now for me. You might want to extract different info from the records though.
This exports to a table (bibliography.tsv) columns containing:
- pmid
- authors
- title
- journal
- year
max_attempts = 5
def fetch_pubmed_data(pmid):
Entrez.email = "[email protected]" # Replace with your email address
handle = Entrez.efetch(db="pubmed", id=pmid, rettype="xml", retmode="text")
record = Entrez.read(handle)
time.sleep(1)
return record
def extract_cited_articles(pmid):
record = fetch_pubmed_data(pmid)
cited_pmids = []
record_article = record['PubmedArticle']
if "PubmedData" in record_article[0] and "ReferenceList" in record_article[0]["PubmedData"]:
for reference in record_article[0]["PubmedData"]["ReferenceList"][0]["Reference"]:
if "ArticleIdList" in reference and len(reference["ArticleIdList"]) > 0:
cited_pmids.append(reference["ArticleIdList"][0])
return cited_pmids
def extract_bibliographic_info(pmid_list, max_attempts):
bibliographic_info = {}
bibliographic_info_ls = []
for pmid in pmid_list:
authors = title = journal = year = ""
record = {}
for attempt in range(max_attempts):
try:
record = fetch_pubmed_data(pmid)
break
except:
time.sleep(5)
if 'PubmedArticle' in record:
if len(record['PubmedArticle']) >0:
article = record['PubmedArticle'][0]["MedlineCitation"]["Article"]
if "AuthorList" in article:
authors = ", ".join([f"{author['LastName']} {author['Initials']}" for author in article["AuthorList"] if 'LastName' in author and 'Initials' in author])
title = article["ArticleTitle"]
journal = article["Journal"]["Title"]
year = article["Journal"]["JournalIssue"]["PubDate"]["Year"]
print (pmid, authors, title, journal, year)
bibliographic_info_ls.append([pmid, authors, title, journal, year])
return bibliographic_info_ls
def main():
pmid = input("Enter the PubMed article ID: ")
cited_pmids = extract_cited_articles(pmid)
bibliographic_info_ls = extract_bibliographic_info(cited_pmids, max_attempts)
df = pd.DataFrame(bibliographic_info_ls, columns=["pmid", "authors", "title", "journal", "year"])
df.to_csv("bibliography.tsv", sep="\t", index=False)
return df
if __name__ == "__main__":
df = main()