我正在尝试使用 trie 数据结构实现拼写检查器。我目前有以下大纲Node
:
class Node:
def __init__(self):
self.next = {}
self.word_marker = False
def add_item(self, string):
#if the length of the string is 0 then return. When the end of the word
#comes set the word_marker to true
if len(string) == 0:
self.word_marker = True
return
#set the key to the first letter of the string and reformat the string to reflect the first letter taken out
#ultimately going to store the letters for each node as the key
key = string[0]
string = string[1:]
#if there is a key in the dictionary, then recursively call add_item with new string
if key in self.next:
self.next[key].add_item(string)
else:
node = Node()
self.next[key] = node
node.add_item(string)
我想做的下一件事是编写函数来搜索 astring
然后返回一个建议的拼写。( def correct(self, string)
)。我将如何通过这个尝试来实现搜索?假设我已经通过定义一个 root node 向 trie 添加了一个单词列表root
,然后add_item
对列表中的每个单词使用。