我有一些以下格式的并行文件。标识符始终相同,并且标识符之间的数字长度相同。文件之间的变化是实际数字。最后,并行文件的数量可以从 2 到 50 不等
>Identifier1
0
1
3
2
0
>Identifier2
0
4
1
>Identifier3
...
由于这些文件很大,(每个约 3.5gb)我不想将它们加载到内存中,而是根据标识符并行解析它们。因此,对于所有文件,选择第一个标识符及其对应的值,并在所有可能的组合之间调用一个函数。然后选择第二个标识符并执行相同的操作...
我尝试解析文件的第一件事如下:
import fileinput
from glob import glob
fnames = glob('tmp/test*')
for line in fileinput.input(fnames):
print(line)
问题在于它一个接一个地解析文件,而不是一次解析所有文件。
第二件事(以某种方式起作用)是使用“with open”手动添加文件。但这不是一个好的选择,因为文件的数量不是固定的。以下代码用于合并两个文件。
from itertools import izip_longest
with open('tmp/test1', 'r') as a, open('tmp/test2', 'r') as b:
flag = true
for x, y in izip_longest(a,b):
first = x.strip()
second = y.strip()
if(first[0]=='>' and second[0]=='>' and first==second):
if(flag is true):
flag = false
identifier = first
d1 = []
d2 = []
else:
print(cor(list(d1),list(d2)))
identifier = first
d1 = []
d2 = []
else:
d1.append(first)
d2.append(second)
要如何改进才能处理多个文件?
更新:
我在网上找到了以下迭代器:
def isheader(line):
return line[0] == '>'
def aspairs(file):
for header,group in itertools.groupby(f, isheader):
if header:
line = group.next()
ensembl_id = line[1:].split()[0]
else:
sequence = ''.join(line.strip() for line in group)
yield ensembl_id, sequence
当我用一个文件测试它时,它正在工作:
with open("tmp/test1") as f:
for l in aspairs(f):
print(l)
我不明白的是如何将它与 Tom 建议的解决方案相结合。
请您参考如下方法:
这是为多个文件名实现 izip 方法的方法:
files = #create a list of filenames
open_files = [open(i, "r") for i in files]
for rows in izip(*open_files):
# rows is now a tuple containing one row from each file
# now you can compare each row with its identifiers
#Don't forget to close the files!
for file in open_files:
file.close()
更新: 好的,我读了你的其他评论,我想我明白你想做什么,所以这是我修改后的代码。这里的要点是我将创建一个名为 numbers_list 的列表列表,它(对于每个标识符)从每个文件中获取一个数字,并将该数字放入与文件“索引”对应的列表中 - 第一个数字(第一行)来自第一个文件的第一个数字将进入第一个列表中的第一个单元格,第二个文件中的第一个数字将进入第二个列表中的第一个单元格,依此类推。(如果不清楚,请通知我)。
import itertools
#create a list of filenames
files = ['file1', 'file2', 'etc...']
open_files = [open(i, "r") for i in files]
flag = TRUE
for rows in izip(*open_files):
#rows is now a tuple containing one row from each file
#use map to create list of string-similar to your x.strip()...
row = map(str.strip, rows)
if (reduce(lambda x, y: x if (x[0] == '>' and x==y) else false, row)):
#not sure if this is what you need
identifier = row[0]
#numers_list would be a list of empty lists similar to d1 = [] d2 = [] but for n-lists: [[],[],...] one for each file
numbers_list = [[] for x in row]
if(flag): #not sure why you need this
flag = FALSE
else:
print(cor(numbers_list))
else:
#This code will append each number from each file to the numbers_list:
#[[first_file_first_num,first_file_second_num,...],[second_file,first_num,second_file_second_num,...],...]
for index, lst in enumerate(numbers_list[:]):
lst.append(row[index])
#Don't forget to close the files!
for file in open_files:
file.close()
