Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.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 - Fatal编程技术网

Python 仅针对某一列的公共值合并两个文本文件

Python 仅针对某一列的公共值合并两个文本文件,python,Python,我有两个文本文件: text1.txt: jose 50 0.037 maria 30 fernando 20 0.489 martin 45 0.078 andres 47 text2.txt: maria 150 0.91 martin 200 0.76 andres 350 0.67 我想复制一下这个: maria 150 0.91 30 martin 200 0

我有两个文本文件:

text1.txt:

jose     50    0.037
maria    30    
fernando 20    0.489
martin   45    0.078
andres   47    
text2.txt:

maria    150    0.91
martin   200    0.76
andres   350    0.67
我想复制一下这个:

maria    150    0.91    30    
martin   200    0.76    45    0.078
andres   350    0.67    47

也就是说,在第一列中只包含来自公共元素的值的组合文件。谢谢。

您可以从每个输入源创建两个字典,用于检查常用名称:

d1 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file1.txt')])
d2 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file2.txt')])
with open('file3.txt', 'w') as f:
  for a, b in d1.items():
     if a in d2:
        f.write(f"{a} {' '.join(d2[a]+b)}\n")
输出:

maria 150 0.91 30
martin 200 0.76 45 0.078
andres 350 0.67 47

您可以从每个输入源创建两个字典,用于检查常用名称:

d1 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file1.txt')])
d2 = (lambda x:{a:b for a, *b in x})([i.strip('\n').split() for i in open('file2.txt')])
with open('file3.txt', 'w') as f:
  for a, b in d1.items():
     if a in d2:
        f.write(f"{a} {' '.join(d2[a]+b)}\n")
输出:

maria 150 0.91 30
martin 200 0.76 45 0.078
andres 350 0.67 47

您编写的程序有什么问题吗?我们可以帮您解决这个问题?请发布您的代码并描述它的错误。粗略地说,您应该选择两个文件中的所有行,然后将列连接在一起。Pandas在这里会很有帮助。请注意,
join text2.txt text1.txt
shell命令完全符合您的要求,尽管它要求对输入文件进行排序。您编写的程序出现了一些问题,我们可以帮您解决吗?请发布您的代码并描述它的错误。粗略地说,您应该选择两个文件中的所有行,然后将列连接在一起。Pandas在这里会很有帮助。请注意,
join text2.txt text1.txt
shell命令完全满足您的要求,尽管它要求对输入文件进行排序