Python txt文件加入字典并查询的方法
时间:2021-04-13 09:11:43|栏目:Python代码|点击: 次
如下所示:
dicFile = open('train_1.txt', 'r')#打开数据
print '开始装载数据...'
txtDict = {}#建立字典
while True:
line = dicFile.readline()
if line == '':
break
index = line.find('\t')#以tab键为分割
key = line[:index]
value = line[index:]
txtDict[key] = value#加入字典
dicFile.close()
##查找字典
srcFile = open('train1.txt', 'r')#要匹配的key
destFile = open('match.txt', 'w')#符合字典的写入里面
while True:
line = srcFile.readline()
if line == '':
break
index = line.find(' ')
key = line[:index]
if txtDict.has_key(key):
destFile.write(key)
destFile.write(txtDict[key])
else:
badFile.write(key)
badFile.write('\n')
print '全部完成!'
destFile.close()
srcFile.close()
上一篇:python 集合 并集、交集 Series list set 转换的实例
栏 目:Python代码
本文地址:http://www.codeinn.net/misctech/100027.html






