【问题标题】:Merging two tsv files by matching items of a column in python通过匹配python中列的项目来合并两个tsv文件
【发布时间】:2017-05-17 01:07:53
【问题描述】:

我有两个制表符分隔 (tsv) 文件。我想在 tsv 文件中获得与两个文件的特定列的项目匹配的输出。我是python新手,如果我能得到一些cmets会很棒。

输入文件1:

#comment one
#comment two and more
ab123    1    339    GT    +  s4
ab222    3    23    CT    -  se4
ab1100    3    523    AA    +  aa11
ab2211    20    166    TT    +  ss

输入文件2:

ab123    1
ab1100    3

通过匹配 file2 的第一列,预期输出是输入 file1 的前 4 列:

ab123    1    339    GT 
ab1100    3    523    AA 

我正在尝试的代码是:

with open("file1") as data:
        for line1 in data:
                with open("file2") as id:
                    for line2 in id:
                        if str(line2) in line1:
                            print line1

【问题讨论】:

    标签: python merge


    【解决方案1】:

    我的方法是使用file1生成一个dict并迭代读取file2生成的列表,并扩展这个列表,然后使用join()方法打印它:

    with open('1.csv') as f1, open('2.csv') as f2:
        d1 = {tuple(i.split()[:2]): i.split()[2:] for i in f1.read().split('\n')}
    
        for i in f2.read().split('\n'):
            tmp = i.split()
            if tuple(tmp[:2]) in d1:
                print(" ".join(tmp+(d1[tuple(tmp[:2])][:2])))
    

    输出:

    ab123 1 339 GT
    ab1100 3 523 AA
    

    希望这会有所帮助。

    【讨论】:

    • 非常感谢。完美地工作@McGrady
    【解决方案2】:

    您可以尝试使用csv 模块读取tab-separated 值文件(tsv 文件),只需提及delimiter='\t',下面是代码:

    import csv
    with open('file1.tsv','rb') as tsv1 , open('file2.tsv', 'rb') as tsv2:
        tsv1 = csv.reader(tsv1, delimiter='\t')    
        tsv2 = csv.reader(tsv2, delimiter='\t')
        tsv1_list=list(tsv1)
        tsv2_list=list(tsv2)
        result = [e1[:4] for e1 in tsv1_list for e2 in tsv2_list if e1[0]==e2[0]]
        print result
    

    输出:

    [['ab123', '1', '339', 'GT'], ['ab1100', '3', '523', 'AA']]
    

    【讨论】:

      猜你喜欢
      • 2016-09-22
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2021-11-21
      • 2011-09-24
      • 2021-10-01
      • 1970-01-01
      • 2015-02-11
      相关资源
      最近更新 更多