在python中使用查找表查找和替换的更快方法

2024-09-29 21:26:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用python中的查找表转换文本文件中的序列ID。要转换的文件可以是任何格式,因此灵活性非常重要。例如:

IDBreakfast    Oatmeal
IDBreakfast    cereal
IDLunch    sandwich

在上面的示例中,IDBreakfast显示在多行上。输入文件也不总是以制表符分隔

查找表具有固定结构,一个旧ID对应一个新ID,制表符分隔:

IDBreakfast    PetitDejeuner
IDLunch    Dejeuner

现在,我逐行读取要转换的文件,然后循环查找表进行查找和替换。这太慢了。我的直觉是我应该在这里使用字典,这会更快吗

infile = open(sys.argv[1],'r')
lookup = open(sys.argv[2],'r')
outfile = open(sys.argv[1]+".converted", 'w')

for line in infile:
    newline = line
    with open(sys.argv[2],'r') as lookup:
        for record in lookup:
            subrecord=record.rstrip()
            old = subrecord.split('\t')[0]
            new = subrecord.split('\t')[1]
            newline = newline.replace(old, new)
    outfile.write(newline)
outfile.close()

Tags: 文件idforsyslinenewlineopenlookup
1条回答
网友
1楼 · 发布于 2024-09-29 21:26:57

字典是一个好方法

import sys

# Create the look up table (dictionary)
lut = {}
with open(sys.argv[2],'r') as lookup:
    for line in lookup:
        if '\t' in line:
            key, value = line.strip().split('\t')
            lut[key] = value

# Go through each line in the input file and replace where applicable
with open(sys.argv[1],'r') as infile, open(sys.argv[1]+".converted", 'w') as outfile:
    for line in infile:
        if '\t' in line:
            key,value = line.strip().split('\t')
            if key in lut:
                outfile.write(f"{key}\t{lut[key]}\n")
            else:
                outfile.write(line)
        else:
            outfile.write(line)

相关问题 更多 >

    热门问题