【问题标题】:Reducing the size of a Trie of all english words减少所有英语单词的 Trie 的大小
【发布时间】: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。

【问题讨论】:

    标签: python trie


    【解决方案1】:

    如果您的 trie 是静态的,这意味着您不需要时不时地在其中插入单词,而是可以“一次性”构建它,那么您需要的结构是 DAFSA,它代表用于有向无环有限状态自动机。如果您的 trie 是动态的,这意味着您需要在其中插入新单词,DAFSA 仍然是答案,但算法要困难得多。

    这基本上是 trie 的压缩版本,它具有相同的访问速度,但在一般情况下所需的空间要低得多。

    将 trie 转换为 DAFSA(有时称为有向无环词图的 DAWG)的算法并不像简单地构建 trie 那样简单,但它们是可以理解的。你应该找到你需要的一切here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 2019-08-05
      • 2017-07-18
      • 1970-01-01
      相关资源
      最近更新 更多