我正在尝试使用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()
字典是一个好方法
相关问题 更多 >
编程相关推荐