在两个文本文件中查找公共值

2024-10-04 09:18:37 发布

您现在位置:Python中文网/ 问答频道 /正文

让我举一个文本文件示例:

例如,在file1.txt数据中,前三列是坐标x y z:

3.6 2.5  0.0 1 c321    
3.0 2.5  0.0 2 c23a
2.4 3.4 10.8 3 cf17
3.6 3.4  6.6 4 bd11

file2.txt中,前两列的数据是:

^{pr2}$

期望结果:

c321 3.6 2.5 0.0    
bd11 3.6 3.4 6.6    
bc2d    
cf17 2.4 3.4 10.8

Tags: 数据txt示例file1file2文本文件pr2c321
1条回答
网友
1楼 · 发布于 2024-10-04 09:18:37

如果是c321、bd11等。。不能重复只使用dict:

from collections import OrderedDict
with open("file1.txt") as f1, open("file2.txt") as f2:
    d = OrderedDict.fromkeys(map(str.rstrip, f2),"")
    for line in f1:
        if line.strip():
            data,k = line.rsplit(None, 1)
            if k in d:
                d[k] = data

for k,v in d.items():
    print(k,v)

输出:

^{pr2}$

如果每行实际上有两列,即:

c321 bd11
bc2d cf17

您需要拆分行以获取每个键:

from collections import OrderedDict
with open("file1.txt") as f1, open("file2.txt") as f2:
    d = OrderedDict((k, "") for line in f2 for k in line.split())
    for line in f1:
        if line.strip():
            data, k = line.rsplit(None, 1)
            if k in d:
                d[k] = data

相关问题 更多 >