运行 编写一次代码来创建一个新文件,并远程使用该文件中的内容? Python

Run code once to create a new file, and use the content in that file remotely? Python

我制作了一个程序来读取 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?

非常感谢您的帮助!请问我的问题是不是很清楚..

它可以通过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)