我打算使用trie数据结构实现自动完成功能。我想将Trie转换为JSON格式。
class Trie(object):
"""Class representing the structure of trie"""
def __init__(self):
self.children={} #Links to other nodes
self.isEndOfWord=False
这是我的trie程序的输出
[
('Z', <search_trie.Trie object at 0x7f3350f32c50>),
('j', <search_trie.Trie object at 0x7f3353e77da0>),
('z', <search_trie.Trie object at 0x7f3350f32be0>),
('M', <search_trie.Trie object at 0x7f33538eb668>)
]
其中:
'Z'-character stored in the trie node
<search_trie.Trie object at 0x7f3350f32c50> -points to other node
如何将其转换为JSON格式?我不希望该对象地址出现在JSON中。如何从地址中提取节点并将其包含在JSON中?
编辑: 这是我的代码。为了避免将节点存储为引用,应该怎么做?如果我可以存储实际的对象值而不是地址,则将其转换为JSON将会很简单。
from functools import reduce
class Trie(object):
"""Class representing the trie"""
def __init__(self):
self.children={}
self.isEndOfWord=False
def add(self,char): #Adds a character to dictionary and creates a new node
self.children[char]=Trie()
def insert(self,word): #Insert a new word to the trie
node=self
for char in word:
if char not in node.children:
node.add(char)
node=node.children[char]
node.isEndOfWord=True
def search(self, word): #Search for a particular word in a trie
node = self
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.isEndOfWord
def all_suffixes(self,prefix):
results = set()
if self.isEndOfWord:
results.add(prefix)
if not self.children:
return results
return reduce(lambda a, b: a | b, [node.all_suffixes(prefix + char) for (char, node) in self.children.items()]) | results
def autocomplete(self, prefix):
node = self
for char in prefix:
if char not in node.children:
return set()
node = node.children[char]
return list(node.all_suffixes(prefix))