python - 多个文件比较

标签 python

我想比较多个文件(15-20),这些文件是 gzip 压缩的,并从它们中恢复常见的行。但这并不那么简单。某些列中的行是准确的,我还希望它们能够计算它们存在的文件数量的信息。如果为 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 字段感兴趣。它们必须在文件之间匹配才能报告为通用。然而,我们仍然需要保留有关其余部分/字段的信息,以便可以将它们写入输出文件

现在我有以下代码:

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

在我当前的代码中,我不知道如何正确实现 if not line.startswith() (哪个位置?),以及如何指定应匹配的行中的列。更不用说,我不知道如何获取 6 个文件中存在的行,或者 15 个文件中 10 个文件中存在的行。 有什么帮助吗?

最佳答案

收集字典中的行以及使它们与键相似的字段:

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)

关于python - 多个文件比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18466518/

相关文章:

python - 有没有办法让 python 解释控制台一次导入我的整个应用程序?

python - Python 并安装 mysql 连接器

python - 如何预处理图像以去除噪声并提取Python文本?

python - 取消维基百科同义词括号

Python Unicode ajax 表单发布错误

python - 每天使用 Django Models 添加新数据

python - 导入错误 : cannot import name 'logsumexp' when importing sklearn. model_selection

python - 如何在 Django 中设置 html 登录页面的用户名和密码?

python - 验证一列中的条件规则和另一列中的重复

Python "denormalize"unicode 组合字符