【问题标题】:comparing two tab seperated files for multiple column and combine matches比较多列的两个制表符分隔文件并合并匹配项
【发布时间】:2018-08-05 15:51:12
【问题描述】:

我需要比较前两列的两个文件,并选择匹配的具有第二个文件的附加信息的文件,例如;

输入1:

0   1
2   4
5   6

输入2:

2   4  xyz
5   4  asv
0   1  qwe

输出是

2   4  xyz
0   1  qwe

我在 python 上试过,但不能正常工作;就像如果第一列有更多 1 它不能给出正确的输出

#!/usr/bin/python

import sys

f1 = 'file1.txt'
f2 = 'file2.txt'

if len(sys.argv) == 3:
    f1 = sys.argv[1]
    f2 = sys.argv[2]

with open(f1) as file_1, open('out.txt', 'w') as of:
    for l1 in file_1:
        col_of_f1 = int(l1.split()[0])
        with open(f2) as file_2:
            for l2 in file_2:
                col_of_f2 = l2.split()
                if len(col_of_f2) < 1:
                    break
                col_of_f2 = int(col_of_f2[0])
                if col_of_f1 == col_of_f2:
                    of.write(l2)
                    break

【问题讨论】:

  • 还有......你尝试了什么,它是如何失败的?
  • 为什么pythonperl 标记霍夫?你能给我们一些代码以便我们帮助你吗?
  • 对于 python 我试过这个但不能正常工作 f1 = 'file1.txt' f2 = 'file2.txt' if len(sys.argv) == 3: f1 = sys.argv[1] f2 = sys.argv[2] with open(f1) as file_1, open('out.txt', 'w') as of: for l1 in file_1: col_of_f1 = int(l1.split()[0]) with open(f2) as file_2: for l2 in file_2: col_of_f2 = l2.split() if len(col_of_f2)

标签: python perl command


【解决方案1】:

在初始化 f1 和 f2 后替换为这段代码

s1=open(f1,'r').read().split('\n')
s2=open(f2,'r').readlines()
of=open('out.txt','w')
ans=''
for i in s1:
    for j in s2:
         if i in j:
             ans+=j+'\n'
of.write(ans)
of.close()

【讨论】:

  • 嗨,我试过了,但它只是直接复制了第一个文件,不要删除或选择常用行
  • 此代码适用于您在问题中提供的输入和输出。试着给出你在问题中给出的输入
猜你喜欢
  • 2017-10-25
  • 1970-01-01
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 2020-12-19
相关资源
最近更新 更多