在两个文本文件中查找常用值

时间:2015-07-26 14:49:11

标签: python python-2.7 python-3.x

让我给出示例文本文件:

e.g。在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前两列的数据是:

c321
bd11    
bc2d    
cf17

期望的结果:

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

1 个答案:

答案 0 :(得分:0)

如果c321,bd11等...不能重复只使用一个字典:

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)

输出:

c321 3.6 2.5 0.0 1
bd11 3.6 3.4 6.6 4
bc2d 
cf17 2.4 3.4 10.8 3

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

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