본문 바로가기
Coding/Python

Biopython으로 Entrez database 탐방하기

by Lv. 35 라이츄 2022. 8. 21.

이것이 그... BLAST 만든 NCBI에 있는 데이터베이스다. 미국답게 스케일 개크다. 


들어가기 전에

보통 Biopython을 쓰거나 랜덤, 넘파이, 판다스를 쓸 때는 뭘 모셔와야 하는데, Entrez에 접속하는 모듈도 마찬가지다. 근데 바이오파이썬은 그걸 떠나서 모셔오는 게 너무 핵가족 스케일이여. 아무튼... 그래서 이번에는 

from Bio import Entrez

이걸 필두로 뭘 많이 모셔올 예정인데... 아니 아직 아냐 마저 듣고 가. 

Entrez에 접속해서 뭘 하려면 저거 말고 필수적으로 입력해야 하는 게 있다. 
1. 너님의 API 키 
2. 너님의 메일 주소
3. 너님의 매개 변수


셋 중 하나는 반드시 입력해야 하고, 여기서는 이메일을 입력할건데 저거 뭐 이메일 제출한다고 CIA에서 당신 털러 오는 거 아니니까 안심하고 쓰자. 오히려 저거 안 쓰면 에러난다. 

 

Einfo

Entrez 자체에 대한 정보를 볼 수 있다. 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com" # 내가 누구인지 말해주는 과정이 필요하다고...
# 자기 이메일 쓰면 됩니다
handle = Entrez.einfo()
result = handle.read()
handle.close()
print(result)
b'<?xml version="1.0" encoding="UTF-8" ?>\n<!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD einfo 20190110//EN" "https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20190110/einfo.dtd">\n<eInfoResult>\n<DbList>\n\n\t<DbName>pubmed</DbName>\n\t<DbName>protein</DbName>\n\t<DbName>nuccore</DbName>\n\t<DbName>ipg</DbName>\n\t<DbName>nucleotide</DbName>\n\t<DbName>structure</DbName>\n\t<DbName>genome</DbName>\n\t<DbName>annotinfo</DbName>\n\t<DbName>assembly</DbName>\n\t<DbName>bioproject</DbName>\n\t<DbName>biosample</DbName>\n\t<DbName>blastdbinfo</DbName>\n\t<DbName>books</DbName>\n\t<DbName>cdd</DbName>\n\t<DbName>clinvar</DbName>\n\t<DbName>gap</DbName>\n\t<DbName>gapplus</DbName>\n\t<DbName>grasp</DbName>\n\t<DbName>dbvar</DbName>\n\t<DbName>gene</DbName>\n\t<DbName>gds</DbName>\n\t<DbName>geoprofiles</DbName>\n\t<DbName>homologene</DbName>\n\t<DbName>medgen</DbName>\n\t<DbName>mesh</DbName>\n\t<DbName>ncbisearch</DbName>\n\t<DbName>nlmcatalog</DbName>\n\t<DbName>omim</DbName>\n\t<DbName>orgtrack</DbName>\n\t<DbName>pmc</DbName>\n\t<DbName>popset</DbName>\n\t<DbName>proteinclusters</DbName>\n\t<DbName>pcassay</DbName>\n\t<DbName>protfam</DbName>\n\t<DbName>biosystems</DbName>\n\t<DbName>pccompound</DbName>\n\t<DbName>pcsubstance</DbName>\n\t<DbName>seqannot</DbName>\n\t<DbName>snp</DbName>\n\t<DbName>sra</DbName>\n\t<DbName>taxonomy</DbName>\n\t<DbName>biocollections</DbName>\n\t<DbName>gtr</DbName>\n</DbList>\n\n</eInfoResult>\n'

...... 아 개비스콘 아저씨 마렵네 이거. 

 

그래서 짤줍했음. 

아니 좀 깔끔하게 못 보여줘요? 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com" # 내가 누구인지 말해주는 과정이 필요하다고...
# 이메일은 자기꺼 그냥 쓰세요
handle = Entrez.einfo()
record = Entrez.read(handle)
handle.close()
print(record)
{'DbList': ['pubmed', 'protein', 'nuccore', 'ipg', 'nucleotide', 'structure', 'genome', 'annotinfo', 'assembly', 'bioproject', 'biosample', 'blastdbinfo', 'books', 'cdd', 'clinvar', 'gap', 'gapplus', 'grasp', 'dbvar', 'gene', 'gds', 'geoprofiles', 'homologene', 'medgen', 'mesh', 'ncbisearch', 'nlmcatalog', 'omim', 'orgtrack', 'pmc', 'popset', 'proteinclusters', 'pcassay', 'protfam', 'biosystems', 'pccompound', 'pcsubstance', 'seqannot', 'snp', 'sra', 'taxonomy', 'biocollections', 'gtr']}

이러시는 이유가 있으실 것 아니예요... 하씨 넘파이 마렵네 이거... 

 

Esearch

이제 본격적으로 찾아볼 시간이다. 핫핫 데이터내놔! 

 

PubMed에서 논문 찾기

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="pubmed", term="biopython[title]", retmax="40" )
record = Entrez.read(handle)
print(record['IdList'])
['34434786', '22909249', '19304878']

바이오파이썬으로 찾았다. (제목에 바이오파이썬이 있는 것) 근데 이 예제 노잼임... 시범조교 불러올거임... 

 

은 바로 이녀석. C. kimchii다. (구 L. kimchii)

김치 related에 당당히 이름을 올렸다. 아니 그야 김치에서 나왔으니까… (자매품으로는 Leuconostoc kimchii도 있다) 근데 얘들아 두부김치도 related 아니냐... 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="pubmed", term="kimchii[title]", retmax="40" )
record = Entrez.read(handle)
print(record['IdList'])
['34320438', '31651376', '31270190', '30361979', '30172442', '29214493', '28920843', '27572507', '27002961', '26370793', '25425317', '25332883', '22140166', '21914872', '21221947', '20494991', '16055277', '15023961', '11931163', '11034505', '11034488']

(대충 개비스콘 아저씨 위장 부여잡는 짤)

 

from Bio import Entrez
import numpy as np
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="pubmed", term="kimchii[title]", retmax="40" )
record = Entrez.read(handle)
result=np.array(record['IdList'])
result=result.reshape(7,3)
print(result)
[['34320438' '31651376' '31270190']
 ['30361979' '30172442' '29214493']
 ['28920843' '27572507' '27002961']
 ['26370793' '25425317' '25332883']
 ['22140166' '21914872' '21221947']
 ['20494991' '16055277' '15023961']
 ['11931163' '11034505' '11034488']]

아 편안하네. 

 

from Bio import Entrez
import numpy as np
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="pubmed", term="kimchii[title] and Leuconostoc[title]", retmax="40" )
record = Entrez.read(handle)
# 출력 안이뻐서 배열 만들었음
result=np.array(record['IdList'])
result=result.reshape(2,4)
print(result)
# 바람직한 출력이야!
[['34320438' '31270190' '30172442' '25425317']
 ['25332883' '21914872' '20494991' '11034505']]

연산자도 먹힌다. 위 코드는 Leuconostoc kimchii를 찾는 연산자. 미역김치 있나요 그건 저거 다 찾아보면 나올듯 

 

Nucleotide DB 찾기

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="nucleotide", term="Arabidopsis[Orgn] AND LHT1[Gene]", idtype="acc")
record = Entrez.read(handle)
print("%s founded" % record["Count"])
print(record["IdList"])
5 founded
['NM_001344354.1', 'NM_180778.4', 'NM_001344353.1', 'NC_003076.8', 'CP002688.1']

애기장대(Arabodopsis)의 LHT1에 대해 찾으면 다섯 개가 나온다. 아까 걔는 없음.. ㅋㅋㅋㅋㅋㅋㅋㅋ 

 

저널 찾기

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esearch(db="nlmcatalog", term="computational[Journal]", retmax="20")
record = Entrez.read(handle)
print("{} computational journals found".format(record["Count"]))
print("The first 20 are\n{}".format(record["IdList"]))
187 computational journals found
The first 20 are
['101775476', '101775136', '468912', '468839', '467370', '101775780', '101774751', '466063', '101768752', '101765300', '101759185', '101752828', '464655', '101768811', '101755127', '101753951', '101753371', '101740904', '101737789', '101736625']

저널? 그럼 이거 인공지능 저널 이런것도 찾아주나? 

 

Epost

있으니까 보고 가긴 하는데 이거 뭔지는 모르겠음... 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
id_list = ["19304878", "18606172", "16403221", "16377612", "14871861", "14630660"]
print(Entrez.epost("pubmed", id=",".join(id_list)).read())
b'<?xml version="1.0" encoding="UTF-8" ?>\n<!DOCTYPE ePostResult PUBLIC "-//NLM//DTD epost 20090526//EN" "https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20090526/epost.dtd"><ePostResult>\n\t<QueryKey>1</QueryKey>\n\t<WebEnv>MCID_618c9fbf207466500268a6a2</WebEnv>\n</ePostResult>\n'

(대충 개비스콘 아저씨 속쓰린 짤)

 

Esummary

검색결과의 첫 번째 데이터에 대해 요약본을 보여준다. 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.esummary(db="pubmed", id="31651376")
record = Entrez.read(handle)
info = record[0]
print("Journal info\nid: {}\nTitle: {}".format(record[0]["Id"], info["Title"]))
Journal info
id: 31651376
Title: <i>Lactococcus kimchii</i> sp. nov., a new lactic acid bacterium isolated from kimchi.

 

Efetch

이거 봤으면 엔트레즈 다 본거다. ...그렇다고 보다말고 가지는 말고... 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
print(handle.read())
LOCUS       EU490707                1302 bp    DNA     linear   PLN 26-JUL-2016
DEFINITION  Selenipedium aequinoctiale maturase K (matK) gene, partial cds;
            chloroplast.
ACCESSION   EU490707
VERSION     EU490707.1
KEYWORDS    .
SOURCE      chloroplast Selenipedium aequinoctiale
  ORGANISM  Selenipedium aequinoctiale
            Eukaryota; Viridiplantae; Streptophyta; Embryophyta; Tracheophyta;
            Spermatophyta; Magnoliopsida; Liliopsida; Asparagales; Orchidaceae;
            Cypripedioideae; Selenipedium.
REFERENCE   1  (bases 1 to 1302)
  AUTHORS   Neubig,K.M., Whitten,W.M., Carlsward,B.S., Blanco,M.A., Endara,L.,
            Williams,N.H. and Moore,M.
  TITLE     Phylogenetic utility of ycf1 in orchids: a plastid gene more
            variable than matK
  JOURNAL   Plant Syst. Evol. 277 (1-2), 75-84 (2009)
REFERENCE   2  (bases 1 to 1302)
  AUTHORS   Neubig,K.M., Whitten,W.M., Carlsward,B.S., Blanco,M.A.,
            Endara,C.L., Williams,N.H. and Moore,M.J.
  TITLE     Direct Submission
  JOURNAL   Submitted (14-FEB-2008) Department of Botany, University of
            Florida, 220 Bartram Hall, Gainesville, FL 32611-8526, USA
FEATURES             Location/Qualifiers
     source          1..1302
                     /organism="Selenipedium aequinoctiale"
                     /organelle="plastid:chloroplast"
                     /mol_type="genomic DNA"
                     /specimen_voucher="FLAS:Blanco 2475"
                     /db_xref="taxon:256374"
     gene            <1..>1302
                     /gene="matK"
     CDS             <1..>1302
                     /gene="matK"
                     /codon_start=1
                     /transl_table=11
                     /product="maturase K"
                     /protein_id="ACC99456.1"
                     /translation="IFYEPVEIFGYDNKSSLVLVKRLITRMYQQNFLISSVNDSNQKG
                     FWGHKHFFSSHFSSQMVSEGFGVILEIPFSSQLVSSLEEKKIPKYQNLRSIHSIFPFL
                     EDKFLHLNYVSDLLIPHPIHLEILVQILQCRIKDVPSLHLLRLLFHEYHNLNSLITSK
                     KFIYAFSKRKKRFLWLLYNSYVYECEYLFQFLRKQSSYLRSTSSGVFLERTHLYVKIE
                     HLLVVCCNSFQRILCFLKDPFMHYVRYQGKAILASKGTLILMKKWKFHLVNFWQSYFH
                     FWSQPYRIHIKQLSNYSFSFLGYFSSVLENHLVVRNQMLENSFIINLLTKKFDTIAPV
                     ISLIGSLSKAQFCTVLGHPISKPIWTDFSDSDILDRFCRICRNLCRYHSGSSKKQVLY
                     RIKYILRLSCARTLARKHKSTVRTFMRRLGSGLLEEFFMEEE"
ORIGIN      
        1 attttttacg aacctgtgga aatttttggt tatgacaata aatctagttt agtacttgtg
       61 aaacgtttaa ttactcgaat gtatcaacag aattttttga tttcttcggt taatgattct
      121 aaccaaaaag gattttgggg gcacaagcat tttttttctt ctcatttttc ttctcaaatg
      181 gtatcagaag gttttggagt cattctggaa attccattct cgtcgcaatt agtatcttct
      241 cttgaagaaa aaaaaatacc aaaatatcag aatttacgat ctattcattc aatatttccc
      301 tttttagaag acaaattttt acatttgaat tatgtgtcag atctactaat accccatccc
      361 atccatctgg aaatcttggt tcaaatcctt caatgccgga tcaaggatgt tccttctttg
      421 catttattgc gattgctttt ccacgaatat cataatttga atagtctcat tacttcaaag
      481 aaattcattt acgccttttc aaaaagaaag aaaagattcc tttggttact atataattct
      541 tatgtatatg aatgcgaata tctattccag tttcttcgta aacagtcttc ttatttacga
      601 tcaacatctt ctggagtctt tcttgagcga acacatttat atgtaaaaat agaacatctt
      661 ctagtagtgt gttgtaattc ttttcagagg atcctatgct ttctcaagga tcctttcatg
      721 cattatgttc gatatcaagg aaaagcaatt ctggcttcaa agggaactct tattctgatg
      781 aagaaatgga aatttcatct tgtgaatttt tggcaatctt attttcactt ttggtctcaa
      841 ccgtatagga ttcatataaa gcaattatcc aactattcct tctcttttct ggggtatttt
      901 tcaagtgtac tagaaaatca tttggtagta agaaatcaaa tgctagagaa ttcatttata
      961 ataaatcttc tgactaagaa attcgatacc atagccccag ttatttctct tattggatca
     1021 ttgtcgaaag ctcaattttg tactgtattg ggtcatccta ttagtaaacc gatctggacc
     1081 gatttctcgg attctgatat tcttgatcga ttttgccgga tatgtagaaa tctttgtcgt
     1141 tatcacagcg gatcctcaaa aaaacaggtt ttgtatcgta taaaatatat acttcgactt
     1201 tcgtgtgcta gaactttggc acggaaacat aaaagtacag tacgcacttt tatgcgaaga
     1261 ttaggttcgg gattattaga agaattcttt atggaagaag aa
//

어... 뭔진 모르겠지만 일단 제가 잘못했어요? 

 

긁어와서 레코드 만들기

from Bio import SeqIO
from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.efetch(db="nucleotide", id="NM_180778.4", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank") # 레코드 형식으로 불러와서 부분적으로 취사선택할 수 있다.
handle.close() # 이거 꼭 닫아야됨?
print(record.description)
Arabidopsis thaliana lysine histidine transporter 1 (LHT1), mRNA

이런 식으로 취사선택해서 보는 것도 된다. 

 

아 긁어왔으면 저장해야지 

참고로 이거 저장은 Entrez 모듈 단독으로 못하고 SeqIO 불러야된다. 

 

from Bio import Entrez
from Bio import SeqIO
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.efetch(db="nucleotide", id="NM_180778.4", rettype="gb", retmode="text")
record=SeqIO.read(handle,"genbank")
handle.close()
print(record)
SeqIO.write(record,"/home/koreanraichu/NM_180778.4.fasta","fasta")
# 사실 여기까진 쿡북에 없었는데 저장할 수 있는 방법이 없나 해서 해봤음.

사실 genbank 포맷인데 저걸 못열어서 fasta로 저장함... 

 

Elink

뭐 관련된 걸 찾아준다고 한다. DNA 시퀀스로 유전자 찾아주듯이... 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
pmid = "19304878"
record = Entrez.read(Entrez.elink(dbfrom="pubmed", id=pmid))
print(record[0]['IdList'])
['19304878']

이런 식으로 쓰고 

for linksetdb in record[0]["LinkSetDb"]:
    print(linksetdb["DbTo"], linksetdb["LinkName"], len(linksetdb["Link"]))
pubmed nuccore_pubmed 1
pubmed nuccore_pubmed_refseq 9
pubmed nuccore_pubmed_weighted 9

for문 먹여도 된단다. 

 

EGQuery

뭐야 쿼리가 왜 여기서 나와요? 그러게요. 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.egquery(term="kimchii")
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
    print(row["DbName"], row["Count"])
pubmed 50
pmc 154
mesh 5
books 0
pubmedhealth Error
omim 0
ncbisearch 4
nuccore 928
nucgss 0
nucest 0
protein 33512
genome 2
structure 0
taxonomy 0
snp 0
dbvar 0
gene 10109
sra 3
biosystems 295
unigene 0
cdd 0
clone 0
popset 25
geoprofiles 0
gds 0
homologene 0
pccompound 0
pcsubstance 0
pcassay 0
nlmcatalog 0
probe 0
gap 0
proteinclusters 0
bioproject 11
biosample 15
biocollections 0

그냥 얘네 DB에 얼마나 있는지가 나온다. 워우. 

 

ESpell

엥? 스펠? 마법사 찍고 올까요? 아니 그거 아냐... 물론 난 작년에 전직했지만 아무튼 그거 아님. 여기서 스펠은 스펠링(철자)의 스펠이지 마법 스펠이 아니다. 

 

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.espell(term="Conpanilactobacillus")
record = Entrez.read(handle)
print(record["Query"])
print(record["CorrectedQuery"])
Conpanilactobacillus
companilactobacillus

위: 오타 교정 전
아래: 오타 교정 후


사용예

개발자가 또 올려놔서 해봤음 

 

Pubmed와 Medline의 대환장 콜라보레이션

일단 최종 코드가 두 개다. 

 

from Bio import Entrez
from Bio import Medline
import numpy as np
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.egquery(term="kimchii")
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
    if row["DbName"] == "pubmed":
        print(row["Count"])
# 쿼리를 통해 kimchii가 들어가는 걸 데려온 다음, pubmed에 있는 것만 뽑았다.
handle = Entrez.esearch(db="pubmed", term="kimchii", retmax=50)
record = Entrez.read(handle)
handle.close()
idlist = record["IdList"]
# 이제 리스트가 많으면 뽑아서 확인할 때 알아서 numpy를 불러봅니다.
handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline",retmode="text")
records = Medline.parse(handle)
# 이렇게 된 이상 medline으로 간다!

handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline",retmode="text")
records = Medline.parse(handle)
for record in records:
    print("title:", record.get("TI", "?"))
    print("authors:", record.get("AU", "?"))
    print("source:", record.get("SO", "?"))
    print("")
# 전체 출력은 여기서(전체 결과 중 제목, 저자, source를 출력)
from Bio import Entrez
from Bio import Medline
import numpy as np
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.egquery(term="kimchii")
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
    if row["DbName"] == "pubmed":
        print(row["Count"])
# 쿼리를 통해 kimchii가 들어가는 걸 데려온 다음, pubmed에 있는 것만 뽑았다.
handle = Entrez.esearch(db="pubmed", term="kimchii", retmax=50)
record = Entrez.read(handle)
handle.close()
idlist = record["IdList"]
# 이제 리스트가 많으면 뽑아서 확인할 때 알아서 numpy를 불러봅니다.
handle = Entrez.efetch(db="pubmed", id=idlist, rettype="medline",retmode="text")
records = Medline.parse(handle)
# 이렇게 된 이상 medline으로 간다!

search_title = "Leuconostoc"
for record in records:
    if not "TI" in record:
        continue
    if search_title in record["TI"]:
        print("Keyword %s found: %s" % (search_title, record["TI"]))
# 제목에 Leuconostoc이 있는 것만 뽑아달라!

위 코드와 아래 코드의 공통 분기는 다음과 같다. 

1. 쿼리로 kimchii 찾아서 
2. pubmed에 있는 것만 뽑아서 
3. ID 리스트업해서 
4. 어디가 찾아야지 

그리고 갈라지는 분기는 여기서 전체 목록을 출력하는가 or Leuconostoc으로 제목을 한번 더 필터링하는가 여부. 저거 둘 다 쓰면 안먹혀서 분기 갈라진거다... 

 

Nucleotide 코드 받기

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.egquery(term="Arabidopsis")
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
    if row["DbName"] == "nuccore":
        print(row["Count"])
# 애기장대로 긁어와서 nuccore에 있는 것만 출력해라
handle = Entrez.esearch(db="nucleotide", term="Arabidopsis", retmax=800, idtype="acc")
record = Entrez.read(handle)
handle.close()
# 올해 얼마나 나왔는지는 모르겠고 일단 800개만 뽑아보자
print(record["IdList"][:5])
idlist = ",".join(record["IdList"][:5])
# 레코드에서 다섯개 뽑아서 리스트업한다.
handle = Entrez.efetch(db="nucleotide", id=idlist, retmode="xml")
records = Entrez.read(handle)
print(records[0].keys())
# 0번째 레코드 키좀 주세요
print(records[0]["GBSeq_length"])
# 시퀀스 길이 줘봐봐

얘도 쿼리 긁는 건 똑같다. 찾는 DB가 다르지... 그리고 예제 코드와 달리 데이터가 방대해서 어쩔 수 없이 위에서 5개만 뽑았다. 안그러면 안끝나 이거... 

 

순순히 Genbank 레코드를 내놓는다면 유혈사태는 면할것이다 

from Bio import Entrez
from Bio import SeqIO
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일
handle = Entrez.egquery(term="Leuconostoc AND kimchii") # 뭐야 연산자 이렇게 쓰면 됨?
record = Entrez.read(handle)
for row in record["eGQueryResult"]:
    if row["DbName"] == "nuccore":
        print(row["Count"])
# nuccore에 수록되어있는 L.kimchii에 대해 찾아보자. (Leuconostoc kimchii)
handle = Entrez.esearch(db="nuccore", term="Leuconostoc AND kimchii")
record = Entrez.read(handle)
gi_list = record["IdList"]
# GI list를 만들어서 출력해보자
gi_str = ",".join(gi_list[0:5])
handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
text = handle.read()
print(text)
# 이거 저장 안됨?
handle = Entrez.efetch(db="nuccore", id=gi_str, rettype="gb", retmode="text")
records = SeqIO.parse(handle, "gb")
for record in records:
    print("%s, length %i, with %i features" % (record.name, len(record), len(record.features)))
# Parsing에는 for문이 국룰이다.

제목 저거 괜찮냐 이쯤되면 parsing에는 for문이 국룰 아니냐... 아무튼. ...아니 잠깐만 쿼리 연산자 저렇게 쓰는거임? 

아무튼 그렇다. 

 

Taxonomy lineage

from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일!!!
handle = Entrez.esearch(db="Taxonomy", term="Lactobacillus")
record = Entrez.read(handle)
print(record['IdList'])
# Taxonomy에서 lactobacillus를 찾아 ID를 내놓아라!
handle = Entrez.efetch(db="Taxonomy", id="1578", retmode="xml")
records = Entrez.read(handle)
print(records[0]['Lineage'])
# Lineage 주세요!
from Bio import Entrez
Entrez.email = "blackholekun@gmail.com"
# 아 맞다 메일!!!
handle = Entrez.esearch(db="Taxonomy", term="Enterococcus")
record = Entrez.read(handle)
print(record['IdList'])
# Taxonomy에서 Enterococcus를 찾아 ID를 내놓아라!
handle = Entrez.efetch(db="Taxonomy", id=record['IdList'], retmode="xml")
records = Entrez.read(handle)
print(records[0]['Lineage'])
# Lineage 주세요!

위 코드와 아래 코드 둘 다 일단 똑같은데, 아래 코드는 taxonomy 번호 결과를 아예 변수로 떄려박아서 다이렉트로 찾아준다. (위 코드는 직접 입력해야 함) 

최근댓글

최근글

skin by © 2024 ttutta