210

Biopython:生物序列与结构数据处理基础

Biopython 是处理生物序列与结构数据的基础库,用于序列解析、PDB 处理与数据库交互。这篇给出最常用的三块能力与实际代码。

Biopython 是生物信息学最基础的 Python 库,1999 年至今持续维护。在 AI 制药流程里它很少是主角,但几乎每条管线都会用到它做序列解析、PDB 文件处理或数据库检索——属于「不显眼但绕不开」的基础设施。

安装

pip install biopython
python -c "import Bio; print(Bio.__version__)"

一、序列处理

from Bio import SeqIO, Align
from Bio.Seq import Seq

# 读写常见格式
for rec in SeqIO.parse("proteins.fasta", "fasta"):
    print(rec.id, len(rec.seq), rec.seq[:30])

# 转录翻译
dna = Seq("ATGGCCATTGTAATGGGCCGCTGAAAGGGTGCCCGATAG")
print(dna.translate(to_stop=True))

# 序列比对(新版用 PairwiseAligner)
aligner = Align.PairwiseAligner(scoring="blastp")
aligner.mode = "local"
alns = aligner.align("MKTVRQERLKS", "MKTAROERLKS")
print(alns.score)
print(alns[0])

注意旧教程里的 Bio.pairwise2 已被弃用,新代码应用 Bio.Align.PairwiseAligner,速度也快很多。

二、PDB 结构处理

from Bio.PDB import PDBParser, PDBIO, Select, PDBList, Superimposer

parser = PDBParser(QUIET=True)
st = parser.get_structure("prot", "1ake.pdb")

# 层级:Structure → Model → Chain → Residue → Atom
for chain in st[0]:
    print(chain.id, len(list(chain.get_residues())))

# 提取单链并去水,写出干净结构
class CleanSelect(Select):
    def accept_residue(self, res):
        return res.id[0] == " "          # 只保留标准残基
    def accept_chain(self, chain):
        return chain.id == "A"

io = PDBIO()
io.set_structure(st)
io.save("chainA_clean.pdb", CleanSelect())

# 结构叠合
sup = Superimposer()
sup.set_atoms(fixed_atoms, moving_atoms)
print("RMSD", sup.rms)

Select 类是它处理 PDB 最实用的机制:通过重写 accept_* 方法就能按任意规则筛选并写出结构,比手工解析文本可靠得多。对接和模拟前的结构准备经常用到。

三、数据库检索

from Bio import Entrez, SeqIO
Entrez.email = "you@example.com"        # NCBI 要求提供邮箱

handle = Entrez.efetch(db="protein", id="NP_000537",
                       rettype="gb", retmode="text")
record = SeqIO.read(handle, "genbank")
print(record.description, len(record.seq))

# 批量下载 PDB
from Bio.PDB import PDBList
pdbl = PDBList()
pdbl.retrieve_pdb_file("1AKE", pdir="structures/", file_format="pdb")

使用 NCBI 接口时要遵守频率限制(无 API key 时约每秒 3 次),批量下载要加延时,否则会被限流。

在 AI 制药流程里的典型位置

  • 准备结构预测输入:从 UniProt/NCBI 拉序列、清洗、切域,再喂给 AlphaFold / ESMFold。
  • 对接前的结构清理:提取目标链、去水去杂原子、保留必要辅因子。
  • 批量结构分析:遍历一批 PDB 算 RMSD、提取序列、统计残基组成。
  • 与专用工具的分工:复杂的结构修复交给 PDBFixer(见 215《PDBFixer》),轨迹分析交给 MDAnalysis(见 205《MDAnalysis》),Biopython 负责解析、筛选、格式转换这类基础活。

上手提示

  • 它是基础设施而非主角,但结构准备与序列处理几乎必用;
  • Select 类是筛选并写出 PDB 最可靠的方式,别手工解析文本;
  • 新代码用 PairwiseAlignerpairwise2 已弃用;
  • 批量访问 NCBI 要设邮箱并控制频率,否则会被限流。

延伸资源