Communitygithub.com

biopython

全面的分子生物學工具包。可用於序列操作、檔案解析(FASTA/GenBank/PDB)、系統發育學以及程式化存取 NCBI/PubMed(Bio.Entrez)。最適合批次處理、自訂生物資訊管線、BLAST 自動化。快速查詢請用 gget;多服務整合請用 bioservices。

biopython 是什麼?

這是一個專為 Python 3.10–3.14 及 PyPy3.10 設計的綜合分子生物學運算工具包(Biopython 1.87),涵蓋序列處理、檔案 I/O、資料庫存取、結構生物資訊、系統發育學等生物資訊任務。主要功能包含 Bio.Seq/SeqIO(序列與格式轉換)、Bio.Align(比對分析)、Bio.Entrez(NCBI 資料庫存取)、Bio.Blast(BLAST 搜尋與解析)、Bio.PDB(蛋白質結構解析)及 Bio.Phylo(系統發育樹操作)。使用此技能時應先閱讀對應的參考文件(如 `references/sequence_io.md`),並遵循設定 Entrez.email、使用迭代器處理大型檔案、妥善關閉連線等最佳實務。該版本修補了 CVE-2025-68463 漏洞,建議用於解析外部 Entrez XML 的工作流程。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/biopython

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Biopython:使用 Python 進行計算分子生物學

概述

Biopython 是一套全面且自由使用的 Python 生物運算工具。它提供序列操作、檔案 I/O、資料庫存取、結構生物資訊、系統發育學及許多其他生物資訊任務的功能。當前版本為 Biopython 1.87(2026 年 3 月 30 日發布)。它支援 Python 3.10-3.14 及 PyPy3.10,並需要 NumPy。Biopython 1.87 在解析不受信任的檔案時也處理了 Bio.Entrez.Parser 中的 CVE-2025-68463,因此對於解析外部提供的 Entrez XML 的工作流程,請優先使用 1.87 或更新版本。

何時使用此技能

請在以下情況使用此技能:

  • 處理生物序列(DNA、RNA 或蛋白質)
  • 讀取、寫入或轉換生物檔案格式(FASTA、GenBank、FASTQ、PDB、mmCIF 等)
  • 透過 Entrez 存取 NCBI 資料庫(GenBank、PubMed、Protein、Gene 等)
  • 執行 BLAST 搜尋或解析 BLAST 結果
  • 進行序列比對(成對或多序列比對)
  • 分析 PDB 檔案中的蛋白質結構
  • 建立、操作或視覺化系統發育樹
  • 尋找序列模體(motif)或分析模體模式
  • 計算序列統計資料(GC 含量、分子量、熔解溫度等)
  • 執行結構生物資訊任務
  • 處理群體遺傳學資料
  • 任何其他計算分子生物學任務

核心功能

Biopython 被組織成模組化的子套件,每個子套件處理特定的生物資訊領域:

  1. 序列處理 - Bio.Seq 和 Bio.SeqIO 用於序列操作和檔案 I/O
  2. 比對分析 - Bio.Align 和 Bio.AlignIO 用於成對和多序列比對
  3. 資料庫存取 - Bio.Entrez 用於程式化存取 NCBI 資料庫
  4. BLAST 操作 - Bio.Blast 用於執行和解析 BLAST 搜尋
  5. 結構生物資訊 - Bio.PDB 用於處理 3D 蛋白質結構
  6. 系統發育學 - Bio.Phylo 用於系統發育樹的操作和視覺化
  7. 進階功能 - 模體、群體遺傳學、序列工具等

安裝與設定

為確保可重現性,請使用明確的版本固定安裝最新的穩定 Biopython 版本:

uv pip install "biopython==1.87"

對於 NCBI 資料庫存取,請務必設定您的電子郵件地址(NCBI 要求)。對於可重複使用的軟體,請設定穩定的 Entrez.tool 值,並向 NCBI 註冊該工具/電子郵件。如需更高的速率限制(每秒 10 個請求而非 3 個),請僅從環境變數讀取 NCBI_API_KEY——請勿硬編碼金鑰或載入不相關的環境變數:

import os
from Bio import Entrez

Entrez.email = "[email protected]"  # 必要——請使用您的真實電子郵件
Entrez.tool = "your_tool_name"  # 可選,但建議用於可重複使用的軟體

# 可選:在 https://www.ncbi.nlm.nih.gov/account/settings/ 註冊
if api_key := os.environ.get("NCBI_API_KEY"):
    Entrez.api_key = api_key

使用此技能

此技能提供按功能領域組織的全面文件。處理任務時,請查閱相關的參考文件:

1. 序列處理(Bio.Seq 與 Bio.SeqIO)

參考文件: references/sequence_io.md

用於:

  • 建立和操作生物序列
  • 讀取和寫入序列檔案(FASTA、GenBank、FASTQ 等)
  • 在檔案格式之間進行轉換
  • 從大型檔案中提取序列
  • 序列轉譯、轉錄和反向互補
  • 使用 SeqRecord 物件

快速範例:

from Bio import SeqIO

# 從 FASTA 檔案讀取序列
for record in SeqIO.parse("sequences.fasta", "fasta"):
    print(f"{record.id}: {len(record.seq)} bp")

# 將 GenBank 轉換為 FASTA
SeqIO.convert("input.gb", "genbank", "output.fasta", "fasta")

2. 比對分析(Bio.Align 與 Bio.AlignIO)

參考文件: references/alignment.md

用於:

  • 成對序列比對(全域和區域)
  • 讀取和寫入多序列比對
  • 使用取代矩陣(BLOSUM、PAM)
  • 計算比對統計資料
  • 自訂比對參數

快速範例:

from Bio import Align

# 成對比對
aligner = Align.PairwiseAligner()
aligner.mode = 'global'
alignments = aligner.align("ACCGGT", "ACGGT")
print(alignments[0])

3. 資料庫存取(Bio.Entrez)

參考文件: references/databases.md

用於:

  • 搜尋 NCBI 資料庫(PubMed、GenBank、Protein、Gene 等)
  • 下載序列和記錄
  • 擷取出版物資訊
  • 跨資料庫尋找相關記錄
  • 使用適當的速率限制進行批次下載

快速範例:

from Bio import Entrez
Entrez.email = "[email protected]"

# 搜尋 PubMed
handle = Entrez.esearch(db="pubmed", term="biopython", retmax=10)
results = Entrez.read(handle)
handle.close()
print(f"找到 {results['Count']} 筆結果")

4. BLAST 操作(Bio.Blast)

參考文件: references/blast.md

用於:

  • 透過 NCBI 網路服務執行 BLAST 搜尋
  • 執行本地 BLAST 搜尋
  • 解析 BLAST XML 輸出
  • 按 E-value 或相似度篩選結果
  • 提取命中序列

快速範例:

from Bio.Blast import NCBIWWW, NCBIXML

# 執行 BLAST 搜尋
result_handle = NCBIWWW.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = NCBIXML.read(result_handle)

# 顯示頂部命中
for alignment in blast_record.alignments[:5]:
    print(f"{alignment.title}: E-value={alignment.hsps[0].expect}")

5. 結構生物資訊(Bio.PDB)

參考文件: references/structure.md

用於:

  • 解析 PDB 和 mmCIF 結構檔案
  • 導覽蛋白質結構層級(SMCRA:結構/模型/鏈/殘基/原子)
  • 計算距離、角度和二面角
  • 二級結構指派(DSSP)
  • 結構疊合和 RMSD 計算
  • 從結構中提取序列

快速範例:

from Bio.PDB import PDBParser

# 解析結構
parser = PDBParser(QUIET=True)
structure = parser.get_structure("1crn", "1crn.pdb")

# 計算兩個 α 碳之間的距離
chain = structure[0]["A"]
distance = chain[10]["CA"] - chain[20]["CA"]
print(f"距離:{distance:.2f} Å")

6. 系統發育學(Bio.Phylo)

參考文件: references/phylogenetics.md

用於:

  • 讀取和寫入系統發育樹(Newick、NEXUS、phyloXML)
  • 從距離矩陣或比對結果建立樹
  • 樹操作(修剪、重新定根、階梯化)
  • 計算系統發育距離
  • 建立一致樹
  • 視覺化樹

快速範例:

from Bio import Phylo

# 讀取並視覺化樹
tree = Phylo.read("tree.nwk", "newick")
Phylo.draw_ascii(tree)

# 計算距離
distance = tree.distance("Species_A", "Species_B")
print(f"距離:{distance:.3f}")

7. 進階功能

參考文件: references/advanced.md

用於:

  • 序列模體(Bio.motifs)- 尋找和分析模體模式
  • 群體遺傳學(Bio.PopGen)- GenePop 檔案、Fst 計算、Hardy-Weinberg 檢定
  • 序列工具(Bio.SeqUtils)- GC 含量、熔解溫度、分子量、蛋白質分析
  • 限制酶分析(Bio.Restriction)- 尋找限制酶切位
  • 分群(Bio.Cluster)- K-means 和階層式分群
  • 基因體圖譜(GenomeDiagram)- 視覺化基因體特徵

快速範例:

from Bio.SeqUtils import gc_fraction, molecular_weight
from Bio.Seq import Seq

seq = Seq("ATCGATCGATCG")
print(f"GC 含量:{gc_fraction(seq):.2%}")
print(f"分子量:{molecular_weight(seq, seq_type='DNA'):.2f} g/mol")

通用工作流程指南

閱讀文件

當使用者詢問特定的 Biopython 任務時:

  1. 根據任務描述識別相關模組
  2. 使用 Read 工具閱讀適當的參考檔案
  3. 提取相關的程式碼模式並根據使用者的特定需求進行調整
  4. 組合多個模組當任務需要時

參考檔案的搜尋模式範例:

# 尋找特定函數的資訊
rg -n "SeqIO.parse" references/sequence_io.md

# 尋找特定任務的範例
rg -n "BLAST" references/blast.md

# 尋找特定概念的資訊
rg -n "alignment" references/alignment.md

撰寫 Biopython 程式碼

撰寫 Biopython 程式碼時請遵循這些原則:

  1. 明確匯入模組

    from Bio import SeqIO, Entrez
    from Bio.Seq import Seq
    
  2. 使用 NCBI 資料庫時設定 Entrez.email;僅從環境變數載入 NCBI_API_KEY(如果存在)

    import os
    from Bio import Entrez
    
    Entrez.email = "[email protected]"
    Entrez.tool = "your_tool_name"
    if api_key := os.environ.get("NCBI_API_KEY"):
        Entrez.api_key = api_key
    
  3. 使用適當的檔案格式 - 檢查哪種格式最適合該任務

    # 常見格式:"fasta"、"genbank"、"fastq"、"clustal"、"phylip"
    
  4. 妥善處理檔案 - 使用後關閉控制代碼或使用內容管理器

    with open("file.fasta") as handle:
        records = SeqIO.parse(handle, "fasta")
    
  5. 對大型檔案使用迭代器 - 避免將所有內容載入記憶體

    for record in SeqIO.parse("large_file.fasta", "fasta"):
        # 一次處理一筆記錄
    
  6. 妥善處理錯誤 - 網路操作和檔案解析可能失敗

    from urllib.error import HTTPError
    
    try:
        handle = Entrez.efetch(db="nucleotide", id=accession)
    except HTTPError as e:
        print(f"錯誤:{e}")
    

常用模式

模式 1:從 GenBank 擷取序列

from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 擷取序列
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()

print(f"描述:{record.description}")
print(f"序列長度:{len(record.seq)}")

模式 2:序列分析管線

from Bio import SeqIO
from Bio.SeqUtils import gc_fraction

for record in SeqIO.parse("sequences.fasta", "fasta"):
    # 計算統計資料
    gc = gc_fraction(record.seq)
    length = len(record.seq)

    # 尋找 ORF、轉譯等
    protein = record.seq.translate()

    print(f"{record.id}: {length} bp, GC={gc:.2%}")

模式 3:BLAST 並擷取頂部命中

from Bio.Blast import NCBIWWW, NCBIXML
from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

# 執行 BLAST
result_handle = NCBIWWW.qblast("blastn", "nt", sequence)
blast_record = NCBIXML.read(result_handle)

# 取得頂部命中的存取號
accessions = [aln.accession for aln in blast_record.alignments[:5]]

# 擷取序列
for acc in accessions:
    handle = Entrez.efetch(db="nucleotide", id=acc, rettype="fasta", retmode="text")
    record = SeqIO.read(handle, "fasta")
    handle.close()
    print(f">{record.description}")

模式 4:從序列建立系統發育樹

from Bio import AlignIO, Phylo
from Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor

# 讀取比對結果
alignment = AlignIO.read("alignment.fasta", "fasta")

# 計算距離
calculator = DistanceCalculator("identity")
dm = calculator.get_distance(alignment)

# 建立樹
constructor = DistanceTreeConstructor()
tree = constructor.nj(dm)

# 視覺化
Phylo.draw_ascii(tree)

最佳實務

  1. 在撰寫程式碼之前務必閱讀相關的參考文件
  2. 使用 grep 搜尋參考檔案以尋找特定函數或範例
  3. 在解析之前驗證檔案格式
  4. 妥善處理遺失的資料 - 並非所有記錄都有所有欄位
  5. 快取下載的資料 - 不要重複下載相同的序列
  6. 尊重 NCBI 的速率限制 - 使用 API 金鑰、為可重複使用的軟體註冊工具/電子郵件值,並對大型作業使用 Entrez 歷史記錄/批次處理
  7. 先用小資料集測試,然後再處理大型檔案
  8. 保持 Biopython 更新以獲得最新的功能和錯誤修正
  9. 使用適當的遺傳密碼表進行轉譯
  10. 記錄分析參數以確保可重現性

常見問題疑難排解

問題:"No handlers could be found for logger 'Bio.Entrez'"

解決方案: 這只是一個警告。設定 Entrez.email 即可抑制它。

問題:來自 NCBI 的 "HTTP Error 400"

解決方案: 檢查 ID/存取號是否有效且格式正確。

問題:解析檔案時出現 "ValueError: EOF"

解決方案: 驗證檔案格式是否與指定的格式字串相符。

問題:比對失敗,顯示 "sequences are not the same length"

解決方案: 在使用 AlignIO 或 MultipleSeqAlignment 之前,確保序列已比對。

問題:BLAST 搜尋速度慢

解決方案: 對於大規模搜尋,請使用本地 BLAST,或快取結果。

問題:PDB 解析器警告

解決方案: 使用 PDBParser(QUIET=True) 來抑制警告,或調查結構品質。

問題:Bio.HMM、Bio.MarkovModel 或 Bio.Application 的 ImportError

解決方案: 這些模組已在 Biopython 1.86 中移除。對於 HMM,請使用 hmmlearn;並使用標準函式庫的 subprocess 模組來替代 Bio.Application CLI 包裝器。

問題:升級到 1.86+ 後 PairwiseAligner 返回的比對結果變少了

解決方案: 預設的缺口分數在 1.86 中從 0 改為 -1,消除了瑣碎的平手比對。如果需要,設定 aligner.gap_score = 0 以恢復舊的行為(請參閱 references/alignment.md)。

其他資源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

cobrapy

Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.

相關技能