# 使用 Bio.Entrez 访问数据库
## 概述
Bio.Entrez 提供了对 NCBI Entrez 数据库(包括 PubMed、GenBank、Gene、Protein、Nucleotide 等)的程序化访问。它处理了 API 调用、速率限制和数据解析的所有复杂性。
## 设置与配置
### 电子邮件地址 (必需)
NCBI 要求提供电子邮件地址以跟踪使用情况,并在出现问题时联系用户:
python
from Bio import Entrez
# 务必设置您的邮箱
Entrez.email = "
[email protected]"
### API Key (推荐)
使用 API Key 可将速率限制从每秒 3 次请求提高到 10 次:
python
# 从此处获取 API Key: https://www.ncbi.nlm.nih.gov/account/settings/
Entrez.api_key = "your_api_key_here"
### 速率限制
Biopython 会自动遵守 NCBI 的速率限制:
- **无 API Key**: 每秒 3 次请求
- **有 API Key**: 每秒 10 次请求
该模块会自动处理此限制,因此无需在请求之间手动添加延迟。
## 核心 Entrez 函数
### EInfo - 数据库信息
获取有关可用数据库及其统计信息的信息:
python
# 列出所有数据库
handle = Entrez.einfo()
result = Entrez.read(handle)
print(result["DbList"])
# 获取特定数据库的信息
handle = Entrez.einfo(db="pubmed")
result = Entrez.read(handle)
print(result["DbInfo"]["Description"])
print(result["DbInfo"]["Count"]) # 记录数量
### ESearch - 搜索数据库
搜索记录并检索其 ID:
python
# 搜索 PubMed
handle = Entrez.esearch(db="pubmed", term="biopython")
result = Entrez.read(handle)
handle.close()
id_list = result["IdList"]
count = result["Count"]
print(f"找到 {count} 条结果")
print(f"检索到的 ID: {id_list}")
### 高级 ESearch 参数
python
# 使用附加参数搜索
handle = Entrez.esearch(
db="pubmed",
term="biopython[Title]",
retmax=100, # 最多返回 100 个 ID
sort="relevance", # 按相关性排序
reldate=365, # 仅限过去一年的结果
datetype="pdat" # 使用发布日期
)
result = Entrez.read(handle)
handle.close()
### ESummary - 获取记录摘要
检索 ID 列表的摘要信息:
python
# 获取多条记录的摘要
handle = Entrez.esummary(db="pubmed", id="19304878,18606172")
results = Entrez.read(handle)
handle.close()
for record in results:
print(f"标题: {record['Title']}")
print(f"作者: {record['AuthorList']}")
prin