多文件比较

2024-09-28 22:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想比较多个gzip文件(15-20),并从中恢复常见的行。但这并不是那么简单。在某些列中是精确的行,而且我想为它们计算它们存在多少文件中的信息。如果为1,则该行对于文件是唯一的,等等。也可以保存这些文件名。你知道吗

每个文件如下所示:

##SAMPLE=<ID=NormalID,Description="Cancer-paired normal sample. Sample ID 'NORMAL'">
##SAMPLE=<ID=CancerID,Description="Cancer sample. Sample ID 'TUMOR'">
#CHROM  POS     ID      REF     ALT     QUAL    FILTER  INFO    FORMAT  NormalID_NORMAL CancerID_TUMOR
chrX    136109567       .       C       CT      .       PASS    IC=8;IHP=8;NT=ref;QSI=35;QSI_NT=35;RC=7;RU=T;SGT=ref->het;SOMATIC;TQSI=1;TQSI_NT=1;phastCons;CSQ=T|ENSG00000165370|ENST00000298110|Transcript|5KB_downstream_variant|||||||||YES|GPR101|||||        DP:DP2:TAR:TIR:TOR:DP50:FDP50:SUBDP50   23:23:21,21:0,0:2,2:21.59:0.33:0.00   33:33:16,16:13,13:4,4:33.38:0.90:0.00
chrX    150462334       .       T       TA      .       PASS    IC=2;IHP=2;NT=ref;QSI=56;QSI_NT=56;RC=1;RU=A;SGT=ref->het;SOMATIC;TQSI=2;TQSI_NT=2;CSQ=A||||intergenic_variant||||||||||||||| DP:DP2:TAR:TIR:TOR:DP50:FDP50:SUBDP50 30:30:30,30:0,0:0,0:31.99:0.00:0.00     37:37:15,17:16,16:6,5:36.7:0.31:0.00

文件以制表符分隔。 如果行以#开头,则忽略该行。我们只对那些不感兴趣的人感兴趣。 采用基于0的python坐标,我们对0,1,2,3,4字段感兴趣。它们必须在文件之间匹配才能作为公共文件报告。但是,我们仍然需要保存关于其余coulmns/字段的信息,以便可以将它们写入输出文件

现在我有以下代码:

import gzip
filenames = ['a','b','c']
files = [gzip.open(name) for name in filenames]

sets = [set(line.strip() for line in file if not line.startswith('#')) for file in files]
common = set.intersection(*sets)
for file in files: file.close()
print common

在我的currenyt代码中,我不知道如何正确实现if-notline.startswith开始()(哪个地方?),以及如何在行中指定应匹配的列。更不用说,我不知道如何得到行,例如在6个文件中,或在总共15个文件中的10个。 有什么帮助吗?你知道吗


Tags: 文件sampleinref信息idforline
1条回答
网友
1楼 · 发布于 2024-09-28 22:34:39

收集字典中与关键字类似的字段中的行:

from collections import defaultdict
d = defaultdict(list)

def process(filename, line):
    if line[0] == '#':
        return

    fields = line.split('\t')
    key = tuple(fields[0:5]) # Fields that makes lines similar/same
    d[key].append((filename, line))

for filename in filenames:
    with gzip.open(filename) as fh:
        for line in fh:
            process(filename, line.strip())

现在,您有了一个包含文件名行元组列表的字典。现在可以打印出现10次以上的所有行:

for l in d.values():
   if len(l) < 10: continue

   print 'Same key found %d times:' % len(l)

   for filename, line in l:
       print '%s: %s' % (filename, line)

相关问题 更多 >