Python 将Trie转换为JSON格式

Python 将Trie转换为JSON格式,python,json,trie,Python,Json,Trie,我计划使用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_tri

我计划使用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>)
]

您的意思是如何将默认对象表示形式更改为JSON?为此,您可以重写
\uuu repr\uuu
方法。您可以使用标准字典()表示trie,然后可以使用
json.dump
将其转换为json文件。您将同意使用字典表示trie。否则,您需要指定表示它的方式(例如,id或哈希)
'Z'-character stored in the trie node

<search_trie.Trie object at 0x7f3350f32c50> -points to other node
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))