Python提取字典中的元素写入新文件的问题
请教一个用Python提取字典中的元素写入新文件的问题。有两个文件,一个文件有一列数据,另外一个文件有两列数据。其中第二个文件的第一列数据和第一个文件列数据有交集。比如:
第一个文件形式:
tom
jam
bill
tom
billy
sam
sam
...
第二个文件形式:
tom teacher
billy student
sam professor
bill ITer
.....
现在想把第一个文件按照第二个文件中的身份对应关系增加一列,如果第二文件中没有对应,就返回成 no hit. 新文件的效果如:
tom teacher
jam no hit
bill ITer
tom teacher
billy student
sam professor
sam professor
拟采用的解决方法: 把第二个文件的每一行构建成字典,然后逐行读入第一个文件,在字典中查找,然后结果写入新的文件中。
代码:
#-*- coding:utf-8 -*
import sys
inF1 = open(sys.argv[1], 'r')
inF2 = open(sys.argv[2], 'r')
outF = open(sys.argv[3], 'w')
lines = [ x.strip().split(',') for x in inF1.readlines() ]
lines2 = [ x.strip().split(',') for x in inF2.readlines() ]
hitDt = {}
for line in lines[1:]:
genetig = line[0]
value = line[1]
hitDt[genetig] = [value]
#字典构建
for line in lines2[1:]:
teg = line[0]
if teg in hitDt.keys():
blastp = hitDt.get(genetig)
hitDt[teg] = [teg, blastp]
else:
hitDt[teg] = [teg,"nohit"]
for hit, value in hitDt.items():
outF.write(hit + '\t' + '\t'.join(map(str,value)) + '\n')
inF1.close()
inF2.close()
outF.close()
运行不出来,不知道哪儿出问题了,请教各位前辈。