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 实现提取某个索引中某个时间段的数据方法

如下所示: from elasticsearch import Elasticsearch import datetime import time import dateutil.p...

Python批量转换文件编码格式

自己写的方法,适用于linux, #!/usr/bin/python #coding=utf-8 import sys import os, os.path import dirca...

python简单文本处理的方法

本文实例讲述了python简单文本处理的方法。分享给大家供大家参考。具体如下: 由于有多线程的影响,c++项目打印出来的时间顺序不一致,导致不太好在excel中统计,故使用python写...

Python定时任务sched模块用法示例

本文实例讲述了Python定时任务sched模块用法。分享给大家供大家参考,具体如下: 通过sched模块可以实现通过自定义时间,自定义函数,自定义优先级来执行函数。 范例一 imp...

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...