网络编程
位置:首页>> 网络编程>> Python编程>> Python txt文件加入字典并查询的方法

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

作者:谁谁的博客  发布时间:2021-11-09 12:50:15 

标签: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()  

来源:https://blog.csdn.net/rooki_men/article/details/52088300

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com