gbkファイルから階級を取得する

## 最初に

gbkファイルは以下のようになっている

```{NC_018118.gbk}
LOCUS       NC_018118              14932 bp    DNA     circular INV 13-JUL-2012
DEFINITION  Elodia flavipalpis mitochondrion, complete genome.
ACCESSION   NC_018118
VERSION     NC_018118.1
DBLINK      Project: 170288
KEYWORDS    RefSeq.
SOURCE      mitochondrion Elodia flavipalpis (parasitic fly)
  ORGANISM  Elodia flavipalpis
            Eukaryota; Metazoa; Ecdysozoa; Arthropoda; Hexapoda; Insecta;
            Pterygota; Neoptera; Holometabola; Diptera; Brachycera;
            Muscomorpha; Oestroidea; Tachinidae; Exoristinae; Goniini; Elodia.
REFERENCE   1  (bases 1 to 14932)
  AUTHORS   Zhao,Z., Su,T.-J. and Zhu,C.-D.
  TITLE     The complete mitochondrial genome of Elodia flavipalpis Aldrich
            (Diptera: Tachinidae) and the evolutionary timescale of tachinid
            flies
  JOURNAL   Unpublished
REFERENCE   2  (bases 1 to 14932)
  CONSRTM   NCBI Genome Project
  TITLE     Direct Submission
  JOURNAL   Submitted (10-JUL-2012) National Center for Biotechnology
            Information, NIH, Bethesda, MD 20894, USA
REFERENCE   3  (bases 1 to 14932)
  AUTHORS   Zhao,Z., Su,T.-J. and Zhu,C.-D.
  TITLE     Direct Submission
  JOURNAL   Submitted (03-JAN-2012) Key Laboratory of Zoological Systematics
            and Evolution, Institute of Zoology, Chinese Academy of Sciences, 1
            Beichen West Road, Chaoyang District, Beijing, Beijing 100101, P.R.
            China
COMMENT     REVIEWED REFSEQ: This record has been curated by NCBI staff. The
            reference sequence is identical to JQ348961.
            COMPLETENESS: full length.
FEATURES             Location/Qualifiers
     source          1..14932
                     /organism="Elodia flavipalpis"
                     /organelle="mitochondrion"
                     /mol_type="genomic DNA"
                     /db_xref="taxon:1146932"
                     /common="parasitic fly"
     tRNA            1..65
                     /product="tRNA-Ile"
\\以下略
```

例えばこのファイルを綱で分類したい時、次のようにする。

## taxonomy IDを取得する

featureからTaxonomy ID を取得する

```python
from Bio import SeqIO, Entrez

Entrez.email = "your mail address"

def get_taxonomyID(record):
    for feature in record.features:
        if feature.type == "source":
            for db_xref in feature.qualifiers["db_xref"]:
                taxonomyID = db_xref.split(":")[1]
                yield taxonomyID 
```

gbkファイル内にtaxonomyIDの記述がなければ取ってくるしかない

```python
for taxa in SeqRecord.annotations["taxonomy"]:
    with Entrez.esearchd(db="Taxonomy", term=taxa) as handle:
       
...
```

## 取得したtaxonomy IDを使って階級を取得する

さっきの関数で取得したTaxonomy IDを投げてエントリを取得する

```python
def get_category_dictionary(taxonomyID):

    with Entrez.efetch(db="Taxonomy", id=taxonomyID, retmode="xml") as handle:
        records = Entrez.read(handle)
    for record in records:
        category_dict = record["LineageEx"]
        yield category_dict
```

## まとめると

```python
from Bio import SeqIO, Entrez

Entrez.email = "your email address"

def get_taxonomyID(record):
    for feature in record.features:
        if feature.type == "source":
            for db_xref in feature.qualifiers["db_xref"]:
                taxonomyID = db_xref.split(":")[1]
                yield taxonomyID 

def get_category_dictionary(taxonomyID):
    with Entrez.efetch(db="Taxonomy", id=taxonomyID, retmode="xml") as handle:
        records = Entrez.read(handle)
    for record in records:
        category_dict = record["LineageEx"]
        yield category_dict


if __name__ == "__main__":
    with open("NC_018118.gbk", "r") as gbkfile:
        for entry in SeqIO.parse(gbkfile, "genbank"):
            for taxonomyID in get_taxonomyID(entry):
                for category_dict_list in get_category_dictionary(taxonomyID):
                    for category_dict in category_dict_list:
                        print(f"{category_dict['ScientificName']} : {category_dict['Rank']}")
````


みたいな感じになります。

実行結果（長いので折りたたみ）
<details><summarry></summary>
<div>

```console
cellular organisms : no rank
Eukaryota : superkingdom
Opisthokonta : no rank
Metazoa : kingdom
Eumetazoa : no rank
Bilateria : no rank
Protostomia : no rank
Ecdysozoa : no rank
Panarthropoda : no rank
Arthropoda : phylum
Mandibulata : no rank
Pancrustacea : no rank
Hexapoda : subphylum
Insecta : class
Dicondylia : no rank
Pterygota : subclass
Neoptera : infraclass
Holometabola : cohort
Diptera : order
Brachycera : suborder
Muscomorpha : infraorder
Eremoneura : no rank
Cyclorrhapha : no rank
Schizophora : no rank
Calyptratae : no rank
Oestroidea : superfamily
Tachinidae : family
Exoristinae : subfamily
Goniini : tribe
Elodia : genus
```
こんな感じで出力されるので、今回のNC_018118はInsectaに分類！みたいなことができます
</div></details>