Python 中的 GeneOntology OBO v1.4 解析器
GeneOntology Consortium 以 OBO v1.2 格式提供 GO 术语的批量数据下载。
如果你 Google GO OBO parser,会发现缺少一些东西。你可以轻松找到 Perl 解析器、Java 解析器,但连 BioPython 都没有 Python 解析器。然而,格式本身似乎为 Python 的生成器概念量身定制。只需要几行 SLOC 就可以让它工作而不将所有内容存储在 RAM 中。
我在一个允许交互式搜索 GO 的原型项目中使用了此解析器(它很快)。我不确定何时/是否会发布它,但这里是解析器代码。
只需将两个函数复制到你的代码库,它除了 Python 标准库中的 collections.defaultdict 外没有任何依赖。
obo_parser.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GeneOntology OBO v1.2 和 v1.4 格式的恒定空间解析器
https://owlcollab.github.io/oboformat/doc/GO.format.obo-1_4.html
版本 1.1:Python3 就绪和 --verbose CLI 选项
"""
from __future__ import with_statement
from collections import defaultdict
__author__ = "Uli Köhler"
__copyright__ = "Copyright 2013 Uli Köhler"
__license__ = "Apache v2.0"
__version__ = "1.1"
def processGOTerm(goTerm):
"""
在表示 GO 术语的对象中,用其唯一成员替换单元素列表。
返回修改后的对象作为字典。
"""
ret = dict(goTerm) #输入是 defaultdict,可能表现出意外行为
for key, value in ret.items():
if len(value) == 1:
ret[key] = value[0]
return ret
def parseGOOBO(filename):
"""
解析 OBO v1.2 格式的 Gene Ontology 转储。
生成每个
关键字参数:
filename:要读取的文件名
"""
with open(filename, "r") as infile:
currentGOTerm = None
for line in infile:
line = line.strip()
if not line: continue #跳过空行
if line == "[Term]":
if currentGOTerm: yield processGOTerm(currentGOTerm)
currentGOTerm = defaultdict(list)
elif line == "[Typedef]":
#跳过 [Typedef] 部分
currentGOTerm = None
else: #不是 [Term]
#仅当我们在 [Term] 环境内时处理
if currentGOTerm is None: continue
key, sep, val = line.partition(":")
currentGOTerm[key].append(val.strip())
#添加最后一个术语
if currentGOTerm is not None:
yield processGOTerm(currentGOTerm)
if __name__ == "__main__":
"""打印给定 GO OBO 文件中 GO 对象的数量"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('infile', help='GO OBO v1.2 格式的输入文件。')
parser.add_argument('-v', '--verbose', action="store_true",
help='打印所有 GO 项而不是仅打印它们的计数')
args = parser.parse_args()
#迭代 GO 术语
termCounter = 0
if args.verbose:
for goTerm in parseGOOBO(args.infile):
print(goTerm)
else:
for goTerm in parseGOOBO(args.infile):
termCounter += 1
print ("Found %d GO terms" % termCounter)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