在文本解析项目中,经常会碰到提取品牌、商家名等需求。如给定一个手机型号字符串,要求从中提取出品牌。Trie可以很好满足此类需求。
Tire,也叫前缀树字典树,是一种数据结构,可以用来快速检索字符串是否存在以及在字符串开始处抽取预定义的子字符串。搜索时间复杂度为O(M) M为字符串长度。

代码实现
Python中无指针,使用Dict实现树结构。
# -*- coding: utf-8 -*-
"""
Trie for prefix search, a data structure that quickly matches and extracts predefined substrings
at the beginning of a given text (if they can be found).
We can also skip certain characters and still succeed in a match.
"""
default_ignored_chars = u' _-/'
class Trie(object):
def __init__(self, items, ignored_chars=default_ignored_chars):
""" Stores all given items