Есть ли способ получить рефераты для данного списка опубликованных идентификаторов?

У меня есть список pmids, я хочу получить рефераты для них обоих в одном URL-адресе.

    pmids=[17284678,9997]
    abstract_dict={}
    url = https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?
    db=pubmed&id=**17284678,9997**&retmode=text&rettype=xml

Мое требование - получить в этом формате

   abstract_dict={"pmid1":"abstract1","pmid2":"abstract2"}

Я могу получить вышеуказанный формат, попробовав каждый идентификатор и обновив словарь, но для оптимизации времени я хочу предоставить все идентификаторы для URL-адреса и обработки и получить только часть рефератов.


person pat    schedule 29.11.2017    source источник


Ответы (1)


Используя BioPython, вы можете передать объединенный список идентификаторов Pubmed Entrez.efetch, и это выполнит поиск по одному URL-адресу:

from Bio import Entrez

Entrez.email = '[email protected]'

pmids = [17284678,9997]
handle = Entrez.efetch(db="pubmed", id=','.join(map(str, pmids)),
                       rettype="xml", retmode="text")
records = Entrez.read(handle)
abstracts = [pubmed_article['MedlineCitation']['Article']['Abstract']['AbstractText'][0]
             for pubmed_article in records['PubmedArticle']]


abstract_dict = dict(zip(pmids, abstracts))

Это дает в результате:

{9997: 'Electron paramagnetic resonance and magnetic susceptibility studies of Chromatium flavocytochrome C552 and its diheme flavin-free subunit at temperatures below 45 degrees K are reported. The results show that in the intact protein and the subunit the two low-spin (S = 1/2) heme irons are distinguishable, giving rise to separate EPR signals. In the intact protein only, one of the heme irons exists in two different low spin environments in the pH range 5.5 to 10.5, while the other remains in a constant environment. Factors influencing the variable heme iron environment also influence flavin reactivity, indicating the existence of a mechanism for heme-flavin interaction.',
 17284678: 'Eimeria tenella is an intracellular protozoan parasite that infects the intestinal tracts of domestic fowl and causes coccidiosis, a serious and sometimes lethal enteritis. Eimeria falls in the same phylum (Apicomplexa) as several human and animal parasites such as Cryptosporidium, Toxoplasma, and the malaria parasite, Plasmodium. Here we report the sequencing and analysis of the first chromosome of E. tenella, a chromosome believed to carry loci associated with drug resistance and known to differ between virulent and attenuated strains of the parasite. The chromosome--which appears to be representative of the genome--is gene-dense and rich in simple-sequence repeats, many of which appear to give rise to repetitive amino acid tracts in the predicted proteins. Most striking is the segmentation of the chromosome into repeat-rich regions peppered with transposon-like elements and telomere-like repeats, alternating with repeat-free regions. Predicted genes differ in character between the two types of segment, and the repeat-rich regions appear to be associated with strain-to-strain variation.'}

Изменить:

В случае pmids без соответствующих аннотаций будьте осторожны с предложенным вами исправлением:

abstracts = [pubmed_article['MedlineCitation']['Article']['Abstract'] ['AbstractText'][0] 
             for pubmed_article in records['PubmedArticle'] if 'Abstract' in
             pubmed_article['MedlineCitation']['Article'].keys()] 

Предположим, у вас есть список идентификаторов Pubmed pmids = [1, 2, 3], но в pmid 2 нет реферата, поэтому abstracts = ['abstract of 1', 'abstract of 3']

Это вызовет проблемы на последнем шаге, где я zip объединяю оба списка вместе, чтобы составить словарь:

>>> abstract_dict = dict(zip(pmids, abstracts))
>>> print(abstract_dict)
{1: 'abstract of 1', 
 2: 'abstract of 3'}

Обратите внимание, что аннотации теперь не синхронизированы с соответствующими идентификаторами Pubmed, потому что вы не отфильтровали pmids без аннотаций и zip обрезаете до самого короткого list.

Вместо этого выполните:

abstract_dict = {}
without_abstract = []

for pubmed_article in records['PubmedArticle']:
    pmid = int(str(pubmed_article['MedlineCitation']['PMID']))
    article = pubmed_article['MedlineCitation']['Article']
    if 'Abstract' in article:
        abstract = article['Abstract']['AbstractText'][0]
        abstract_dict[pmid] = abstract
    else:
       without_abstract.append(pmid)

print(abstract_dict)
print(without_abstract)
person BioGeek    schedule 30.11.2017
comment
Я попробовал ваш код, он работает над некоторыми аспектами и выдает «Ключевую ошибку» в других, где статьи не имеют рефератов. Ниже прикреплен 'KeyError' code ---------------------------------------------------------- -------------------------------- KeyError Traceback (последний последний вызов) ‹ipython-input-34-382b1b6b6529› в ‹module›() 1 abstracts = [pubmed_article['MedlineCitation']['Article']['Abstract']['AbstractText'][0] ----› 2 для pubmed_article в записях['PubmedArticle'] 3 ] KeyError: «Абстрактный» - person pat; 30.11.2017
comment
code abstracts = [pubmed_article['MedlineCitation']['Article']['Abstract'] ['AbstractText'][0] для pubmed_article в записях['PubmedArticle'], если 'Abstract' в pubmed_article['MedlineCitation'][' Статья'].keys()] - person pat; 30.11.2017
comment
Обратите внимание, что теперь вам нужно будет отфильтровать идентификаторы Pubmed без рефератов из pmids, иначе abstract_dict будет не синхронизировано. Смотрите мою правку. - person BioGeek; 01.12.2017
comment
Код, который вы добавили, будет правильно отфильтровывать pmids с рефератами и без них. Мне вот немного любопытно. Если у pmid нет реферата, у него может быть заголовок для статьи, поэтому я хочу получить заголовки тех pmid, у которых нет рефератов. Я выбрал этот подход, чтобы не оставлять pmid'ы, не имеющие рефератов. - person pat; 01.12.2017