关于 alterlab-biopython
Biopython 是面向生物信息学工作的 Python 工具集,适用于处理序列、数据库和分子结构等任务。此技能按功能整理文档与代码模式,并提示重要 API 变更。
主要功能
- 01生物序列处理与格式读写
- 02NCBI 数据库访问
- 03BLAST 搜索与结果解析
- 04序列比对与统计
- 05蛋白质结构分析
- 06系统发育树操作与可视化
适用场景
- 01转换 FASTA、GenBank 等序列文件
- 02检索 NCBI 并下载序列或文献信息
- 03比对序列并解析 BLAST 结果
- 04分析 PDB 结构或绘制系统发育树
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ alterlab-ieu/ alterlab-academic-skills --skill alterlab-biopython安装后在 Claude Code 中输入/alterlab-biopython确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
evals/evals.jsonreferences/advanced.mdalignment.mdblast.mddatabases.mdphylogenetics.mdsequence_io.mdstructure.md详细介绍
Biopython:使用 Python 进行计算分子生物学
概述
Biopython 是一套全面且免费提供的 Python 生物计算工具。它提供序列操作、文件输入/输出、数据库访问、结构生物信息学、系统发育学以及许多其他生物信息学任务所需的功能。当前版本为 Biopython 1.88(2026 年 8 月),支持 Python 3.10–3.14,并且需要 NumPy。
需留意的已移除/已变更 API
- 命令行封装器已移除。
Bio.Application及其所有衍生内容——Bio.Blast.Applications(Ncbiblastn/p/x…Commandline、NcbimakeblastdbCommandline)和Bio.Align.Applications(ClustalOmegaCommandline、MuscleCommandline)——已在 1.78 版弃用,并在 1.86 版移除。请通过subprocess调用可执行文件(参见references/blast.md和references/alignment.md)。- PairwiseAligner 的 gap 分数在 1.86 版发生了变化。 默认 gap 分数现在为 -1 (之前为 0),因此使用默认设置的比对器返回的非退化比对结果会少得多。 gap 属性也已重命名为插入/缺失形式 (
open_internal_insertion_score,……);*_gap_score名称仍可作为 元属性使用。alphabet属性已弃用且不再使用。Bio.pairwise2已弃用——请改用Bio.Align.PairwiseAligner。Bio.Blast.NCBIXML已声明为过时 API:从 1.89 开发线开始,推荐使用 1.84 版新增的Bio.Blast解析器(Blast.parse/Blast.read、Blast.qblast)。 它仍随 1.88 版提供且可正常工作;新代码请优先使用新 API。- 值得为安全修复升级的版本: 1.87 修复了
Bio.Entrez.Parser中的 CVE-2025-68463, 1.88 则移除了Bio.Nexus解析器中的一个eval,该问题可能导致通过恶意 NEXUS 文件执行代码。请将下载的记录视为不可信输入,并保持 Biopython 为最新版本。
何时使用此技能
适用于以下情况:
- 处理生物序列(DNA、RNA 或蛋白质)
- 读取、写入或转换生物文件格式(FASTA、GenBank、FASTQ、PDB、mmCIF 等)
- 通过 Entrez 访问 NCBI 数据库(GenBank、PubMed、Protein、Gene 等)
- 执行 BLAST 搜索或解析 BLAST 结果
- 执行序列比对(双序列或多序列比对)
- 分析 PDB 文件中的蛋白质结构
- 创建、操作或可视化系统发育树
- 查找序列基序或分析基序模式
- 计算序列统计数据(GC 含量、分子量、熔解温度等)
- 执行结构生物信息学任务
- 处理群体遗传学数据
- 执行其他计算分子生物学任务
不适用的情况
| 场景 | 改用 |
|---|---|
从命令行运行本地 BLAST+/makeblastdb,或 DIAMOND | alterlab-blast |
| 单次查询某个基因、序列或结构 | alterlab-gget |
| 在一个流程中调用多个 Web 服务(UniProt + KEGG + ChEMBL) | alterlab-bioservices |
| SAM/BAM/CRAM 记录访问、pileup 和 reads 过滤 | alterlab-pysam |
| 从未比对的序列构建 ML 系统发育树(MAFFT + IQ-TREE) | alterlab-phylogenetics |
核心功能
Biopython 由多个模块化子包组成,分别针对特定的生物信息学领域:
- 序列处理 - 使用 Bio.Seq 和 Bio.SeqIO 操作序列并进行文件输入/输出
- 比对分析 - 使用 Bio.Align 和 Bio.AlignIO 执行双序列和多序列比对
- 数据库访问 - 使用 Bio.Entrez 以编程方式访问 NCBI 数据库
- BLAST 操作 - 使用 Bio.Blast 运行和解析 BLAST 搜索
- 结构生物信息学 - 使用 Bio.PDB 处理 3D 蛋白质结构
- 系统发育学 - 使用 Bio.Phylo 操作和可视化系统发育树
- 高级功能 - 基序、群体遗传学、序列工具等
安装和设置
安装 Biopython(需要 Python 3 和 NumPy)。在此机器上,优先使用 uv run 运行脚本:
# Ad-hoc: run a script with Biopython available, no venv to manage
uv run --with biopython script.py
# Or add it to a project
uv add biopython
访问 NCBI 数据库时,务必设置你的电子邮件地址(NCBI 要求):
from Bio import Entrez
Entrez.email = "[email protected]"
# Optional: API key for higher rate limits (10 req/s instead of 3 req/s)
Entrez.api_key = "your_api_key_here"
使用此技能
此技能提供了按功能领域组织的完整文档。处理任务时,请查阅相关参考文档:
1. 序列处理(Bio.Seq 和 Bio.SeqIO)
参考: references/sequence_io.md
适用于:
- 创建和操作生物序列
- 读取和写入序列文件(FASTA、GenBank、FASTQ 等)
- 在不同文件格式之间转换
- 从大型文件中提取序列
- 序列翻译、转录和反向互补
- 使用 SeqRecord 对象
快速示例:
from Bio import SeqIO
# Read sequences from FASTA file
for record in SeqIO.parse("sequences.fasta", "fasta"):
print(f"{record.id}: {len(record.seq)} bp")
# Convert GenBank to FASTA
SeqIO.convert("input.gb", "genbank", "output.fasta", "fasta")
2. 比对分析(Bio.Align 和 Bio.AlignIO)
参考: references/alignment.md
适用于:
- 两两序列比对(全局和局部)
- 读取和写入多序列比对
- 使用替换矩阵(BLOSUM、PAM)
- 计算比对统计数据
- 自定义比对参数
快速示例:
from Bio import Align
# Pairwise alignment
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]"
# Search PubMed
handle = Entrez.esearch(db="pubmed", term="biopython", retmax=10)
results = Entrez.read(handle)
handle.close()
print(f"Found {results['Count']} results")
4. BLAST 操作(Bio.Blast)
参考: references/blast.md
适用于:
- 通过 NCBI Web 服务运行 BLAST 搜索
- 运行本地 BLAST 搜索
- 解析 BLAST XML 输出
- 按 E-value 或一致性筛选结果
- 提取命中序列
快速示例(Bio.Blast API 于 1.84 版本引入 — NCBI 要求提供联系邮箱):
from Bio import Blast
Blast.email = "[email protected]"
result_stream = Blast.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = Blast.read(result_stream)
# Each hit's alignments are Bio.Align objects; scores live in .annotations
for hit in blast_record[:5]:
print(f"{hit.target.id}: E-value={hit[0].annotations['evalue']}")
5. 结构生物信息学(Bio.PDB)
参考: references/structure.md
适用于:
- 解析 PDB 和 mmCIF 结构文件
- 遍历蛋白质结构层级(SMCRA:Structure/Model/Chain/Residue/Atom)
- 计算距离、角度和二面角
- 指定二级结构(DSSP)
- 结构叠合和 RMSD 计算
- 从结构中提取序列
快速示例:
from Bio.PDB import PDBParser
# Parse structure
parser = PDBParser(QUIET=True)
structure = parser.get_structure("1crn", "1crn.pdb")
# Calculate distance between alpha carbons
chain = structure[0]["A"]
distance = chain[10]["CA"] - chain[20]["CA"]
print(f"Distance: {distance:.2f} Å")
6. 系统发育学(Bio.Phylo)
参考: references/phylogenetics.md
适用于:
- 读取和写入系统发育树(Newick、NEXUS、phyloXML)
- 根据距离矩阵或比对结果构建树
- 操作树(剪枝、重新定根、梯状排列)
- 计算系统发育距离
- 创建共识树
- 可视化树
快速示例:
from Bio import Phylo
# Read and visualize tree
tree = Phylo.read("tree.nwk", "newick")
Phylo.draw_ascii(tree)
# Calculate distance
distance = tree.distance("Species_A", "Species_B")
print(f"Distance: {distance:.3f}")
7. 高级功能
参考: references/advanced.md
适用于:
- 序列基序(Bio.motifs)— 查找和分析基序模式
- 群体遗传学(Bio.PopGen)— GenePop 文件、Fst 计算、哈代-温伯格检验
- 序列工具(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 content: {gc_fraction(seq):.2%}")
print(f"Molecular weight: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol")
通用工作流指南
阅读文档
当用户询问特定的 Biopython 任务时:
- 根据任务描述确定相关模块
- 使用 Read 工具阅读相应的参考文件
- 提取相关代码模式,并根据用户的具体需求进行调整
- 根据任务需要组合多个模块
参考文件的搜索模式示例:
# Find information about specific functions
grep -n "SeqIO.parse" references/sequence_io.md
# Find examples of specific tasks
grep -n "BLAST" references/blast.md
# Find information about specific concepts
grep -n "alignment" references/alignment.md
编写 Biopython 代码
编写 Biopython 代码时,请遵循以下原则:
-
显式导入模块
from Bio import SeqIO, Entrez from Bio.Seq import Seq -
使用 NCBI 数据库时设置 Entrez 邮箱
Entrez.email = "[email protected]" -
使用合适的文件格式 - 检查哪种格式最适合该任务
# Common formats: "fasta", "genbank", "fastq", "clustal", "phylip" -
妥善处理文件 - 使用后关闭句柄,或使用上下文管理器
with open("file.fasta") as handle: records = SeqIO.parse(handle, "fasta") -
处理大型文件时使用迭代器 - 避免将所有内容都加载到内存中
for record in SeqIO.parse("large_file.fasta", "fasta"): # Process one record at a time -
妥善处理错误 - 网络操作和文件解析都可能失败
try: handle = Entrez.efetch(db="nucleotide", id=accession) except HTTPError as e: print(f"Error: {e}")
常见模式
模式 1:从 GenBank 获取序列
from Bio import Entrez, SeqIO
Entrez.email = "[email protected]"
# Fetch sequence
handle = Entrez.efetch(db="nucleotide", id="EU490707", rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
handle.close()
print(f"Description: {record.description}")
print(f"Sequence length: {len(record.seq)}")
模式 2:序列分析工作流
from Bio import SeqIO
from Bio.SeqUtils import gc_fraction
for record in SeqIO.parse("sequences.fasta", "fasta"):
# Calculate statistics
gc = gc_fraction(record.seq)
length = len(record.seq)
# Find ORFs, translate, etc.
protein = record.seq.translate()
print(f"{record.id}: {length} bp, GC={gc:.2%}")
模式 3:BLAST 并获取排名靠前的命中结果
from Bio import Blast, Entrez, SeqIO
Entrez.email = Blast.email = "[email protected]"
# Run BLAST (Bio.Blast API, Biopython >= 1.84)
result_stream = Blast.qblast("blastn", "nt", sequence)
blast_record = Blast.read(result_stream)
# Get top hit accessions (hit.target is a SeqRecord)
accessions = [hit.target.name for hit in blast_record[:5]]
# Fetch sequences
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
# Read alignment
alignment = AlignIO.read("alignment.fasta", "fasta")
# Calculate distances
calculator = DistanceCalculator("identity")
dm = calculator.get_distance(alignment)
# Build tree
constructor = DistanceTreeConstructor()
tree = constructor.nj(dm)
# Visualize
Phylo.draw_ascii(tree)
最佳实践
- 编写代码前务必阅读相关参考文档
- 使用 grep 在参考文件中搜索特定函数或示例
- 解析前验证文件格式
- 妥善处理缺失数据 - 并非所有记录都包含所有字段
- 缓存下载的数据 - 不要反复下载相同的序列
- 遵守 NCBI 速率限制 - 使用 API 密钥并设置适当的延迟
- 处理大型文件前先用小型数据集测试
- 保持 Biopython 为最新版本,以获取最新功能和错误修复
- 使用合适的遗传密码表进行翻译
- 记录分析参数,以确保可复现性
常见问题排查
问题:"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) 抑制警告,或检查结构质量。
更多资源
- 官方文档:https://biopython.org/docs/latest/
- 教程:https://biopython.org/docs/latest/Tutorial/
- 食谱:https://biopython.org/docs/latest/Tutorial/(高级示例)
- GitHub:https://github.com/biopython/biopython
- 邮件列表:[email protected]
快速参考
要在参考文件中查找信息,请使用以下搜索模式:
# Search for specific functions
grep -n "function_name" references/*.md
# Find examples of specific tasks
grep -n "example" references/sequence_io.md
# Find all occurrences of a module
grep -n "Bio.Seq" references/*.md
总结
Biopython 为计算分子生物学提供了全面的工具。使用此技能时:
- 确定任务领域(序列、比对、数据库、BLAST、结构、系统发育或高级主题)
- 查阅
references/目录中的相应参考文件 - 根据具体用例调整代码示例
- 根据需要组合多个模块,以处理复杂工作流
- 遵循文件处理、错误检查和数据管理方面的最佳实践
模块化的参考文档确保了每项主要 Biopython 功能都有详细且可搜索的信息。
AlterLab Academic Skills 套件的一部分。