- 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文件加入字典並查詢
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.