UnicodeDecodeError при использовании Biopython для получения аннотации от efetch

Недавно, используя Biopython для извлечения реферата из Pubmed. Мой код написан на Python3, как показано ниже:

from Bio import Entrez

Entrez.email = "[email protected]"    # Always tell NCBI who you are


def get_number():    #Get the total number of abstract available in Pubmed
    handle = Entrez.egquery(term="allergic contact dermatitis ")
    record = Entrez.read(handle)
    for row in record["eGQueryResult"]:
        if row["DbName"]=="pubmed":
            return int(row["Count"])


def get_id():    #Get all the ID of the abstract available in Pubmed
    handle = Entrez.esearch(db="pubmed", term="allergic contact dermatitis ", retmax=200)
    record = Entrez.read(handle)
    idlist = record["IdList"]
    return idlist

idlist = get_id()

for ids in idlist:    #Download the abstract based on their ID
    handle = Entrez.efetch(db="pubmed", id=ids, rettype="abstract", retmode="text")    # Retmode Can Be txt / json / xml / csv
    f = open("{}.txt".format(ids), "w")    # Create a TXT file with the name of ID
    f.write(handle.read())    #Write the abstract to the TXT file

Я хочу получить 200 аннотаций, но мне удается получить только три или четыре абстракции. Затем возникает ошибка:

UnicodeDecodeError: 'cp950' codec can't decode byte 0xc5 in position 288: illegal multibyte sequence

Кажется, что у handle.read() есть проблемы с теми рефератами, в которых есть определенные символы или слова. Я пытаюсь использовать print, чтобы узнать класс handle:

handle = Entrez.efetch(db="pubmed", id=idlist, rettype="abstract", retmode="text")
print(handle)

Результат:

<_io.TextIOWrapper encoding='cp950'>

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


person K. Yu    schedule 21.03.2017    source источник
comment
См. также github.com/biopython/biopython/issues/1402.   -  person peterjc    schedule 06.10.2017


Ответы (1)


Для меня ваш код работает нормально. Проблема с кодировкой на вашем сайте. Вы можете открыть файл в байтовом режиме и закодировать текст в utf-8. Вы можете попробовать обходной путь следующим образом:

for ids in idlist:    #Download the abstract based on their ID
    handle = Entrez.efetch(db="pubmed", id=ids, rettype="abstract", retmode="text")    # Retmode Can Be txt / json / xml / csv
    f = open("{}.txt".format(ids), "wb")    # Create a TXT file with the name of ID
    f.write(handle.read().encode('utf-8'))
person Martyna    schedule 22.03.2017