Pel*_*eus 1 python bash compare match
我有两个文本文件,格式。
File 1
Column A Column B
File 2
Column B Column C
Run Code Online (Sandbox Code Playgroud)
在文件 2 中,B 列只是文件 1 中数据的一个子集。
我希望搜索文件 1,如果在文件 2 中找到与 B 列数据点匹配的内容,则打印 A 列值。
谁能建议如何以简单的方式做到这一点?最好是 Python 或 Bash。
非常感谢。
一个例子
File 1
Bruce Dog
Frank Cat
Adam Fish
Alex Horse
File 2
Dog Blue
Fish Green
Run Code Online (Sandbox Code Playgroud)
会打印:
Bruce
Adam
Run Code Online (Sandbox Code Playgroud)
这可以通过使用字典轻松实现
示例实现
from itertools import imap
file2 = dict(imap(str.split, open("file2")))
with open("file1") as fin:
for key, value in imap(str.split, fin):
if value in file2:
print key
Run Code Online (Sandbox Code Playgroud)
OP注意事项
如果您担心由于文件句柄未显式关闭而导致资源泄漏,请将第一条语句括在 with 子句中
with open("file2") as fin:
file2 = dict(imap(str.split, fin))
Run Code Online (Sandbox Code Playgroud)