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

yipeiwu_com6年前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的Django框架中设置日期和字段可选的方法

设置字段可选 在摆弄了一会之后,你或许会发现管理工具有个限制:编辑表单需要你填写每一个字段,然而在有些情况下,你想要某些字段是可选的。 举个例子,我们想要Author模块中的email字...

【python】matplotlib动态显示详解

【python】matplotlib动态显示详解

1.matplotlib动态绘图 python在绘图的时候,需要开启 interactive mode。核心代码如下: plt.ion(); #开启interactive mode...

一个超级简单的python web程序

在MAC/LINUX环境下,执行vi hello.py命令,并输入以下代码 import web import sys urls = ("/Service/hello","hel...

Python中IPYTHON入门实例

本文实例讲述了Python中IPYTHON用法。分享给大家供大家参考。具体分析如下: 1. 使用TAB补全功能 2. 配置IPYTHON .ipython目录中的是一个名为ipy_use...

python 异或加密字符串的实例

做个简单习题:输入明文给定秘钥,密文还原,按位异或处理。 import base64 as b64 def xor_encrypt(tips,key): ltips=len(ti...