Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在两个文本文件中查找公共值_Python_Python 2.7_Python 3.x - Fatal编程技术网

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

Python 在两个文本文件中查找公共值,python,python-2.7,python-3.x,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

让我给出示例文本文件:

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

如果是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)
输出:

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

我有两个文本文件,其中包含共享值,我希望每个公共值都显示它们的坐标(@Clodion),这意味着如果您自己尝试过?发布您的代码,社区可以提供帮助。@瓦利德·瓦利德:我的问题是,您试图在哪里解决这个问题。您说的两栏是什么意思,在您的示例输入中只有一个?因此,实际上每行有两列?我编辑了我的示例,现在您可以在文件2中看到两列供您使用的Bank you Padraicpatience@oualidwalid:下次请将所有相关信息放在问题的第一个版本中。你浪费了时间来得到正确的答案,而帕德雷克·坎宁安浪费了时间来回答错误的问题。