Skip to main content
 首页 » 编程设计

python之从两个文件的特定列中查找匹配项

2025年05月04日10leader

我有两个不同长度的文件,但都有 3 个制表符分隔的列。 File2 的行数约为 5,000,000,000,File1 的行数为 2,000,000:

文件1:

abc foo bar 
lmn potato rst 
lmp tomato  asd 

文件2:

123 asdasc  dad 
032 foo 2134 
123 linkin  9123 
42  cads    asd 
45654   tomato  12123 

我需要使用第 2 列作为匹配两个文件的键,如果第 2 列匹配,则从 File1 和 File2 中提取行

fout = open('outfile', 'w') 
with open('file1', 'r') as f1, open('file2', 'r') as f2: 
  file2_keys = [i.split('\t')[1] for i in f2] 
  for line in f1: 
    if line.split('\t')[1] in file2_keys: 
      print>>fout, line 

但这只给了我来自 File1 的行。

期望的输出应该是

输出文件 2:

032 foo 2134 
45654   tomato  12123 

输出文件 1:

abc foo bar 
lmp tomato  asd 

有没有办法在 unix 中有效地做到这一点?还有什么方法可以有效地做到这一点?

请您参考如下方法:

Is there a way to do it in unix effectively?

您可以使用 awk。

awk 'NR==FNR{a[$2]=$2;next}{if ($2 in a) {print $0}}' File1 File2 

将从 File1 产生所需的输出:

032 foo 2134 
45654   tomato 12123 

同样,

awk 'NR==FNR{a[$2]=$2;next}{if ($2 in a) {print $0}}' File2 File1 

将从 File2 产生所需的输出:

abc foo bar 
lmp tomato  asd