首页 > 编程 > Python > 正文

Python txt文件加入字典并查询的方法

2019-11-25 13:28:56
字体:
来源:转载
供稿:网友

如下所示:

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 txt文件加入字典并查询的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表