在 Python 中读取 UniProt 文本格式
就像计算生物学中的许多其他数据库一样,流行的 UniProt 数据库的下载以自定义文本格式提供,文档见 ExPASy。
虽然编写通用解析器肯定不难,也可以使用 BioPython,但我认为使用仅使用标准库的经过测试的解析器通常更容易。
此代码提供了一个易于使用的基于生成器的流式解析器,将记录解析为类字典对象。字段内的换行符始终保留。解析器假设文件是 UTF-8 编码的。
read_uniprot.py
#!/usr/bin/env python3
"""
UniProt 文本格式的简单读取器,可从
http://www.uniprot.org/downloads 下载
"""
import gzip
from collections import defaultdict
__author__ = "Uli Köhler"
__copyright__ = "Copyright 2014, Uli Koehler"
__license__ = "Apache License v2.0"
__version__ = "1.0"
def readUniprot(fin):
"""给定类文件对象,生成 uniprot 对象"""
lastKey = None # 最后遇到的键
currentEntry = defaultdict(str)
for line in fin:
key = line[:2].decode("ascii")
#处理新条目
if key == "//":
yield currentEntry
currentEntry = defaultdict(str)
#SQ 字段除了第一行外没有行头
if key == " ":
key = lastKey
lastKey = key
#值应为 ASCII,否则我们假设 UTF8
value = line[5:].decode("utf-8")
currentEntry[key] += value
#如果还有非空条目,打印它
if currentEntry:
yield currentEntry
if __name__ == "__main__":
#如何使用 readUniprot() 的示例
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("file")
args = parser.parse_args()
with gzip.open(args.file, "rb") as infile:
#readUniprot() 生成所有文档
for uniprot in readUniprot(infile):
print(uniprot)Check out similar posts by category:
Bioinformatics, Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow