mcpField
B
biopython

biopython

github.com/jackspace数据与数据库1637 次安装12 周前更新
代码仓库

关于 biopython

Biopython 是用于计算分子生物学的 Python 工具集,面向处理生物数据的研究人员和开发者。其模块涵盖序列与文件处理、数据库访问、BLAST、结构分析和系统发育。

主要功能

  1. 01操作序列和生物学文件
  2. 02通过 Entrez 访问 NCBI 数据库
  3. 03运行并解析 BLAST 搜索
  4. 04分析蛋白质结构
  5. 05构建和操作系统发育树

适用场景

  1. 01转换 FASTA 和 GenBank 记录
  2. 02比对 DNA、RNA 或蛋白质序列
  3. 03从 NCBI 获取记录
  4. 04检查 PDB 结构或系统发育树

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jackspace/claudeskillz --skill biopython

安装后在 Claude Code 中输入/biopython确认已加载。

附带文件SKILL.json

详细介绍

Biopython:Python 中的计算分子生物学

概述

Biopython 是一套全面且可免费获取的 Python 生物计算工具。它提供序列操作、文件 I/O、数据库访问、结构生物信息学、系统发育分析以及许多其他生物信息学任务的功能。当前版本是 Biopython 1.85(2025 年 1 月发布),支持 Python 3,并需要 NumPy。

何时使用此技能

在以下情况下使用此技能:

  • 处理生物序列(DNA、RNA 或蛋白质)
  • 读取、写入或转换生物文件格式(FASTA、GenBank、FASTQ、PDB、mmCIF 等)
  • 通过 Entrez 访问 NCBI 数据库(GenBank、PubMed、Protein、Gene 等)
  • 运行 BLAST 搜索或解析 BLAST 结果
  • 执行序列比对(双序列比对或多序列比对)
  • 分析 PDB 文件中的蛋白质结构
  • 创建、操作或可视化系统发育树
  • 查找序列基序或分析基序模式
  • 计算序列统计信息(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. 高级功能 - 基序、群体遗传学、序列实用工具等

安装与设置

使用 pip 安装 Biopython(需要 Python 3 和 NumPy):

pip install 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 或同一性过滤结果
  • 提取命中序列

快速示例:

from Bio.Blast import NCBIWWW, NCBIXML

# Run BLAST search
result_handle = NCBIWWW.qblast("blastn", "nt", "ATCGATCGATCG")
blast_record = NCBIXML.read(result_handle)

# Display top hits
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: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 计算、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 content: {gc_fraction(seq):.2%}")
print(f"Molecular weight: {molecular_weight(seq, seq_type='DNA'):.2f} g/mol")

通用工作流指南

阅读文档

当用户询问特定的 Biopython 任务时:

  1. 根据任务描述确定相关模块
  2. 使用 Read 工具阅读相应的参考文件
  3. 提取相关代码模式,并将其适配到用户的具体需求
  4. 在任务需要时组合多个模块

参考文件的示例搜索模式:

# 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 代码时遵循以下原则:

  1. 显式导入模块

    from Bio import SeqIO, Entrez
    from Bio.Seq import Seq
    
  2. 使用 NCBI 数据库时设置 Entrez 邮箱

    Entrez.email = "[email protected]"
    
  3. 使用合适的文件格式 - 检查哪种格式最适合该任务

    # Common formats: "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"):
        # Process one record at a time
    
  6. 优雅地处理错误 - 网络操作和文件解析可能会失败

    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.Blast import NCBIWWW, NCBIXML
from Bio import Entrez, SeqIO

Entrez.email = "[email protected]"

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

# Get top hit accessions
accessions = [aln.accession for aln in blast_record.alignments[: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)

最佳实践

  1. 编写代码前始终阅读相关参考文档
  2. 使用 grep 搜索参考文件中的特定函数或示例
  3. 在解析前验证文件格式
  4. 优雅地处理缺失数据 - 并非所有记录都包含所有字段
  5. 缓存下载的数据 - 不要重复下载相同的序列
  6. 遵守 NCBI 速率限制 - 使用 API 密钥和适当的延迟
  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) 抑制警告,或检查结构质量。

其他资源

快速参考

要在参考文件中定位信息,请使用以下搜索模式:

# 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 为计算分子生物学提供了全面的工具。使用此技能时:

  1. 确定任务领域(序列、比对、数据库、BLAST、结构、系统发育学或高级主题)
  2. 查阅 references/ 目录中相应的参考文件
  3. 根据具体用例调整代码示例
  4. 在需要处理复杂工作流时组合多个模块
  5. 遵循最佳实践,进行文件处理、错误检查与数据管理

模块化的参考文档确保为 Biopython 的每一项主要功能提供详细、可搜索的信息。

评论

支持 Markdown