【发布时间】:2019-06-17 08:55:05
【问题描述】:
我正在使用 Trie 实现自动完成功能。使用this 链接中的单词列表,我将每个单词都插入到我的 Trie 中。我想减少 Trie 使用的内存,而不使用像有向无环词图这样的花哨的东西。
Trie 是基于字典的,允许将其存储在 JSON 文件中。这是我当前的脚本:
import json
#Make a trie of english words
# The words file can be found at https://github.com/dwyl/english-words
with open('words_dictionary.json', 'r') as file:
words = json.load(file)
_end = '_end_'
trie = {}
def make_trie(words):
root = trie
for word in words:
current = root
for char in word:
if char not in current:
current[char] = {}
current = current[char]
current[_end] = _end
make_trie(words)
with open('word_trie.json', 'w') as outfile:
json.dump(trie, outfile)
如果可以的话,请帮我写代码sn-ps。
【问题讨论】: