脚本专栏 
首页 > 脚本专栏 > 浏览文章

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

(编辑:jimmy 日期: 2025/5/16 浏览:3 次 )

如下所示:

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

上一篇:使用CodeMirror实现Python3在线编辑器的示例代码
下一篇:python 根据时间来生成唯一的字符串方法
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网 网站地图 SiteMap