【发布时间】:2013-07-13 00:30:12
【问题描述】:
我正在尝试使用 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)
接下来我要做的是编写函数来搜索string,然后返回建议的拼写。 (def correct(self, string))。我将如何通过这个尝试来实现搜索?假设我已经通过定义一个根节点root 向树中添加了一个单词列表,然后对列表中的每个单词使用add_item。
【问题讨论】:
-
d.has_key(k)真的是老帽子了;使用k in d -
很酷的感谢会做出改变