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

Python txt文件加入字典并查询的方法,第1张

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

如下所示:

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/3277715.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-10-05
下一篇 2022-10-05

发表评论

登录后才能评论

评论列表(0条)

保存