python - 如何从两个制表符分隔的文件中获取枢轴线?

标签 python shell csv dictionary hashmap

给定两个文件 file1.txt

abc def \t 123 456
jkl mno \t 987 654
foo bar \t 789 123
bar bar \t 432 
file2.txt
foo bar \t hello world
abc def \t good morning
xyz \t 456
任务是提取第一列匹配的行并实现:
abc def \t 123 456 \t good morning
foo bar \t 789 123 \t hello world
我可以在 Python 中这样做:
from io import StringIO

file1 = """abc def \t 123 456
jkl mno \t 987 654
foo bar \t 789 123
bar bar \t 432"""


file2 = """foo bar \t hello world
abc def \t good morning
xyz \t 456"""

map1, map2 = {}, {}

with StringIO(file1) as fin1:
    for line in file1.split('\n'):
        one, two = line.strip().split('\t')
        map1[one] = two
    
    
with StringIO(file2) as fin2:
    for line in file2.split('\n'):
        one, two = line.strip().split('\t')
        map2[one] = two
        
        
for k in set(map1).intersection(set(map2)):
    print('\t'.join([k, map1[k], map2[k]]))
实际的任务文件有数十亿行, 是否有更快的解决方案,而无需加载所有内容并保留哈希图/字典?
也许使用 unix/bash 命令?对文件进行预排序有帮助吗?

最佳答案

join 命令有时很难使用,但这里很简单:

join -t $'\t' <(sort file1.txt) <(sort file2.txt)
它使用 bash 的 ANSI-C quoting 指定制表符分隔符,使用 process substitutions 将程序输出视为文件。
要查看输出,请将上述内容通过管道输入 cat -A 以查看表示为 ^I 的选项卡:
abc def^I123 456^Igood morning$
foo bar^I789 123^Ihello world$

关于python - 如何从两个制表符分隔的文件中获取枢轴线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66121376/

相关文章:

python - 读取由 s3 事件触发的文件

python - 为什么 macOS Visual Studio Code 使用错误的 Python 解释器?

csv - 从CSV文件创建Hive表时的唯一ID

python - 如何将数据框转换为csv?

linux - 使用文字双引号从 bash 脚本生成文本

php - 使用 ansible 运行 php 脚本会抛出错误

python - Python 中带有子进程的 Shell 管道

Python os.name 在 Windows 7 上返回 nt

python - 使用文件输出自动创建目录

python - 在Python中求解动态数非线性方程