在 Python 中读取 matblas 替换矩阵
问题:
你想将 matblas 格式的替换矩阵(例如来自 NCBI 的此 BLOSUM62)读入 numpy ndarray。
解决方案
使用此代码片段:
read_matblas.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import with_statement
import numpy
__author__ = "Uli Köhler"
__license__ = "Apache License v2.0"
__version__ = "1.0"
def readMatblasAlignmentMatrix(filename):
"""
读取 matblas 格式的替换矩阵。
关键字参数:
filename:要从中读取矩阵的文件名
返回元组(列/行列表,numpy 替换矩阵)
"""
with open(filename) as infile:
currentRow = 0
for line in infile:
if line.startswith("#"): continue
elif line.startswith(" "): #列指示器
columns = line.split()
matrix = numpy.empty((len(columns), len(columns)), dtype=numpy.int32)
else: #矩阵行
parts = line.split()
assert(len(parts) == len(columns) + 1)
#假设行的顺序与列相同
assert(columns[currentRow] == parts[0])
matrix[:,currentRow] = parts[1:]
currentRow += 1
return (columns, matrix)Check out similar posts by category:
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