引言
在做中文分词的项目中,需要重复读取词库中的数据。因此如果简单得将词库中的词语读取到列表中会降低会降低每次扫描的效率。于是采用Trie(字典树)的数据结构来进行存储。
在这篇博文中,已经对Trie的原理做了比较清楚的解释。相比于英文,中文其实是可以通过utf-8
编码存储的,把一个汉字分成三个字节,每个字节存储在一个节点里。
在此就不多说了,直接上代码。
class TrieNode(object):
def __init__(self):
self.value = None
self.children = {}
class Trie(object):
def __init__(self):
self.root = TrieNode()
def add(self, words):
"""Add a string to this trie."""
words = words.encode("utf-8")
p = self.root
n = len(words)
i = 0
for word in words:
if word not in p.children:
new_node = TrieNode()
p.children[word] = new_node
p = new_node
else:
p = p.children[word]
# end
i += 1
if i == n:
p.value = words
def search(self, words):
"""Judge whether s is in this trie."""
words = words.encode("utf-8")
p = self.root
n = len(words)
i =0
for word in words:
if word not in p.children:
return False
p = p.children[word]
i += 1
if i == n:
if p.value:
return p.value
else:
return False
return False
if __name__ == '__main__':
trie = Trie()
trie.add('中文')
trie.add("abcde")
end1 = trie.search("中文")
end2 = trie.search("abcde")
print(end1.decode())
print(end2.decode())
输出为:
中文
abcde
由于仅用于存储,所以就写了add
和search
两个功能,仅做参考。