我创建了一个程序,它读取usr / share / dict / words文件并创建具有相同字母的键值对(例如,bkkooorw:['bookwork','workbook'])
我想稍后使用这本词典找到像这样的词
print dictpairs['bkkoorw'] # >>> bookwork workbook
这个工作正常,但我不想每次运行程序时都要创建一个字典,因为这需要花费很多时间,字典中的单词不会改变。
那么,我如何阅读usr / share / dict / words并使用字典的内容创建一个新文件,dictpairs(不编辑单词文件)。并保存,然后我可以从当前程序访问该字典数据。 ?
from datetime import datetime
start_time = datetime.now()
import itertools
f = open('/usr/share/dict/words', 'r')
dictpairs = {} #create dictionary to later use remotely
for word in f:
sortedword = ''.join(sorted(word))[1:]
if sortedword in dictpairs:
dictpairs[sortedword].append(word[:-1])
else:
dictpairs[sortedword] = [word[:-1]]
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time)) #takes too long to run every time. I only need to run this once since the contents in usr/share/dict/word won't change.
print dictpairs['bkkoorw'] #how do i use dictpairs remotely?
非常感谢你的帮助!请问我的问题是不是很清楚......
答案 0 :(得分:0)
它可以通过pickle
存储在本地驱动器中import pickle
dictpairs = {'bkkooorw' : ['bookwork', 'workbook']}
#store your dict
with open(fileName, 'wb') as handle:
pickle.dump(dictpairs , handle)
#load your dict
with open(fileName, 'rb') as handle:
dictpairs = pickle.load(handle)