Python txt文件加入字典並查詢

  1. dicFile = open('train_1.txt''r')#打開數據  
  2. print '開始裝載數據...'  
  3. txtDict = {}#建立字典  
  4. while True:  
  5.     line = dicFile.readline()  
  6.     if line == '':  
  7.         break  
  8.     index = line.find('\t')#以tab鍵爲分割  
  9.     key = line[:index]  
  10.     value = line[index:]  
  11.     txtDict[key] = value#加入字典  
  12. dicFile.close()  
  13. ##查找字典  
  14. srcFile = open('train1.txt''r')#要匹配的key  
  15. destFile = open('match.txt''w')#符合字典的寫入裏面  
  16. while True:  
  17.     line = srcFile.readline()  
  18.     if line == '':  
  19.         break  
  20.     index = line.find(' ')  
  21.     key = line[:index]  
  22.     if txtDict.has_key(key):      
  23.         destFile.write(key)  
  24.         destFile.write(txtDict[key])         
  25.     else:  
  26.         badFile.write(key)  
  27.         badFile.write('\n')  
  28. print '全部完成!'  
  29. destFile.close()  
  30. srcFile.close()  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章