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

yipeiwu_com5年前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 txt文件加入字典并查询的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python双端队列原理、实现与使用方法分析

本文实例讲述了python双端队列原理、实现与使用方法。分享给大家供大家参考,具体如下: 双端队列 双端队列(deque,全名double-ended queue),是一种具有队列和栈的...

Win10系统下安装labelme及json文件批量转化方法

Win10系统下安装labelme及json文件批量转化方法

一、安装环境:windows10,anaconda3,python3.6 由于框架maskrcnn需要json数据集,在没安装labelme环境和跑深度学习之前,我安装的是anacond...

详解python opencv、scikit-image和PIL图像处理库比较

详解python opencv、scikit-image和PIL图像处理库比较

进行深度学习时,对图像进行预处理的过程是非常重要的,使用pytorch或者TensorFlow时需要对图像进行预处理以及展示来观看处理效果,因此对python中的图像处理框架进行图像的读...

python执行get提交的方法

本文实例讲述了python执行get提交的方法。分享给大家供大家参考。具体如下: import sys, urllib2, urllib def addGETdata(url, da...

django如何自己创建一个中间件

django如何自己创建一个中间件

中间件是什么? 中间件是类似flask函数中钩子函数的东西。可以在请求视图函数前,或者视图函数响应后处理某些事情。中间件对全部视图都有效! 中间件一般会有两个方法,process_r...