比较python中两个tsv文件中的部分行

时间:2016-09-21 16:04:27

标签: python csv compare

所以我想在一个文件中对与给定行匹配的值进行求和/分析,以匹配另一个文件。 我想要比较的第一个文件的格式是:

Acetobacter cibinongensis   Acetobacter Acetobacteraceae    
Rhodospirillales    Proteobacteria  Bacteria    
Acetobacter ghanensis   Acetobacter Acetobacteraceae    Rhodospirillales    Proteobacteria  Bacteria    
Acetobacter pasteurianus    Acetobacter Acetobacteraceae    Rhodospirillales    Proteobacteria  Bacteria

第二个文件就像:

Blochmannia endosymbiont of Polyrhachis (Hedomyrma) turneri Candidatus Blochmannia  Enterobacteriaceae  Enterobacteriales   Proteobacteria  Bacteria    1990    7.511    14946.9
Blochmannia endosymbiont of Polyrhachis (Hedomyrma) turneri Candidatus Blochmannia  Enterobacteriaceae  Enterobacteriales   Proteobacteria  Bacteria    2061    6.451    13295.5
Calyptogena okutanii thioautotrophic gill symbiont  Proteobacteria-undef    Proteobacteria-undef    Proteobacteria-undef    Proteobacteria  Bacteria    7121    2.466    17560.4

我想要做的是解析第一个文件中的每一行,并且对于第一个6个字段匹配的第二个文件中的每一行,对物种信息后面的3个字段中的数字进行分析。

我的代码如下:

with open('file1', 'r') as file1:
with open('file2', 'r') as file2:
    for line in file1:
        count = 0
        line = line.split("\t")
        for l in file2:
            l = l.split("\t")
            if l[0:6] == line[0:6]:
                count+=1
        count = str(count)
        print line + '\t' + count +'\t'+'\n'

我希望我能从第一个文件中获取该行以及在第二个文件中找到该物种的次数。 我知道可能有更好的方法来完成分析的这个特定部分,但我想给出一个简单的目标示例。 无论如何,我没有得到任何匹配,即我从未看到过实例 l [0:6] ==行[0:6] 是真的。 有任何想法吗?? :-S

1 个答案:

答案 0 :(得分:0)

根本原因是你在第一次迭代时消耗file2,然后它总是迭代过来。

快速修复:完全读取file2并将其放入列表中。然而,就速度而言,这是相当低效的(O(N ^ 2):双环)。如果使用key = tuple中的6个第一个值创建一个字典,可能会更好。

with open('file2', 'r') as f:
    file2 = list(f)
with open('file1', 'r') as file1:

    for line in file1:
        count = 0
        line = line.split("\t")
        for l in file2:
            l = l.split("\t")
            if l[0:6] == line[0:6]:
                count+=1
        count = str(count)
        print line + '\t' + count +'\t'+'\n'

此外,使用配置了TAB的csv模块作为分隔符可以避免将来出现一些意外。

更好的版本,使用字典更快地访问file2的数据(前6个元素是关键,请注意我们不能使用list作为关键字,因为它是可变的但是我们必须将其转换为tuple):

d = dict()

# create the dictionary from file2
with open('file2', 'r') as file2:
    for l in file2:
        fields = l.split("\t")
        d[tuple(fields[0:6])] = fields[6:]

# iterate through file1, and use dict lookup on data of file2
# much, much faster if file2 contains a lot of data

with open('file1', 'r') as file1:

    for line in file1:
        count = 0
        line = line.split("\t")

        if tuple(line[0:6]) in d:  # check if in dictionary
            count+=1
            # we could extract the extra data by accessing
            # d[tuple(line[0:6])]
        count = str(count)
        print(line + '\t' + count +'\t'+'\n')
相关问题