如果第一列与另一个文件匹配,则获取文件中的行?

如果第一列与另一个文件匹配,则获取文件中的行?

我有两个文本文件(制表符分隔)。如果文件 2 中的第一列或 ID 匹配,我希望从文件 2 中获取一行。示例如下:

文件一:

115
147
222
322

文件2:

0   AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
1   AAAAAAAAAAAAAAAAAAA
22  GACGGCA 
34  AAAAAATTTTTTTTAAAAAAAAAAAAA
25  GACGGCAAAAAAAAAAAAAAAAA 
115 AAAAAAAAAAAAAAAAGGGGGGGGGGAAAAAAA
147 GGGGGGGGTTTTTTTTTAAAAAAAA
222 GACGGGAA
322 AAAAAATTTTTTTTAAAAAAAAAAAAA

期望的输出:

115 AAAAAAAAAAAAAAAAGGGGGGGGGGAAAAAAA
147 GGGGGGGGTTTTTTTTTAAAAAAAA
222 GACGGGAA
322 AAAAAATTTTTTTTAAAAAAAAAAAAA

答案1

Python 解决方案:

with open('file1.txt') as f1:
    ids = set(f1.read().splitlines())

with open('file2.txt') as f2, open('file3.txt', 'w') as f3:
    lines = f2.read().splitlines()
    for line in lines:
        id = line.split()[0]
        if id in ids:
            f3.write(line + '\n')

相关内容