python - 避免在函数中重复加载文件
问题描述
我正在尝试编写一个具有获取fasta文件的函数的文件,并且(i)概述文件,(ii)绘制序列长度分布的直方图。我成功编写了以下有效的代码:
from Bio import SeqIO
from prettytable import PrettyTable
import pylab
import numpy as np
import sys
%matplotlib inline
def fasta_outlook(fasta_file):
'''Summarize the fasta file with #ofseq, length(min,max). Takes filename as string'''
=> sizes = [len(rec) for rec in SeqIO.parse(fasta_file,"fasta")]
table = PrettyTable(['Parameter', 'Stats'])
table.add_row(['No. of Sequences', len(sizes)])
table.add_row(['Shortest seq.length', min(sizes)])
table.add_row(['Longest Seq.length', max(sizes)])
print(table)
def fasta_burst(fasta_file):
'''Reports the length of each fasta sequence in the file. Takes filename as string'''
my_file = open("Seq_length.tab","w")
=> for rec in SeqIO.parse(fasta_file,"fasta"):
my_file.write(rec.id+'\t'+str(len(rec))+'\n')
print("Length report written in Seq_length.tab")
def fasta_lendist(fasta_file):
'''plot the distribution of sequence length as histogram. Takes filename as string'''
=> sizes = [len(rec) for rec in SeqIO.parse(fasta_file,"fasta")]
count,bins,_ = pylab.hist(sizes, bins=100, log=True, histtype='step',color='red')
pylab.title("%i seq with len: %i to %i bp (range)\nBin Max: %i seq around %i bp"%(len(sizes),min(sizes),max(sizes),count.max(),bins[np.argmax(count)]))
pylab.xlabel("Sequence length (bp)")
pylab.ylabel("Log Count")
pylab.savefig("Sequence_length_distribution_plot.png")
print("Plot saved as Sequence_length_distribution_plot.png")
fasta = 'filename.fa'
fasta_outlook(fasta)
fasta_lendist(fasta)
这里的问题是,在所有函数中我重复加载文件(=>)。是否可以仅全局加载一次文件并在后续函数中使用该对象?函数的 arg 是否采用对象而不是文件名(字符串)?
解决方案
看起来您只使用文件中的记录长度和 ID。您可以将它们加载到元组列表或两个单独的列表中并传递它们。当然没有理由一遍又一遍地解析你的文件。
首先编写一个函数来加载相关数据。我认为一对列表更好,因为您只使用一次 ID:
def load_file(filename):
data = [(rec.id, len(rec)) for rec in SeqIO.parse(fasta_file, "fasta")]
# Transpose the data into two lists instead of list of pairs
return tuple(map(list, zip(*data)))
现在你的函数调用应该看起来像
fasta = 'filename.fa'
ids, sizes = load_file(fasta)
fasta_outlook(sizes)
fasta_lendist(sizes)
fasta_burst(ids, sizes)
在fasta_outlook
andfasta_lendist
中,您只需将输入参数名称更改为sizes
并删除计算这些值的理解。在fasta_burst
中,您可以稍微简化循环:
def fasta_burst(ids, sizes):
'''Reports the length of each fasta sequence in the file. Takes filename as string'''
with open("Seq_length.tab","w") as my_file:
for id, rec in zip(ids, sizes):
my_file.write('{}\t{}\n'.format(id, size))
print("Length report written in Seq_length.tab")
使用with
块确保您的文件在完成后关闭。您之前根本没有关闭,并且with
即使发生错误也可以关闭。
推荐阅读
- java - crashlytics 仪表板没有出现?或 crashlytics 未启用?
- python - 将二进制文件转换为 proto 文件
- r - 忽略 R 中置信区间 (CI) 的 NA
- rust - 为什么过滤 Vec 时会出现双重引用?
- blazor - Blazor EditForm 添加 InputNumber 字段
- c - 带有 SSL 和连接缓存的 libcurl 长轮询
- oracle - 动态操作重定向到 Oracle Apex 中的另一个页面
- sql - 是否使用从 Excel 到 SQL 的日期条件进行计数?
- laravel - Nuxt 项目尝试通过 Laravel Sanctum 登录用户时抛出 CSRF 令牌不匹配 419 错误
- random - 如何约束非零值的字对齐地址?