Trie后缀树Python简单实现

本文介绍了一种使用Python实现Trie树的方法,并提供了一个具体的示例。通过该示例,读者可以了解到如何创建Trie树并对其进行序列计数。此外,还介绍了如何将构建好的Trie树序列化为文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on Dec 17, 2012


@author: honghe
'''


import pickle


class TrieNode(object):
    def __init__(self):
        self.count = 1  # 统计此结点代表的字符串出现的次数
        self.children = {}  
        
class Trie(object):
    def __init__(self):
        self.root = TrieNode()
        
    def add(self, sequence):
        node = self.root
        for c in sequence:
            if c not in node.children:
                child = TrieNode()
                node.children[c] = child
                node = child
            else:
                node = node.children[c]
                node.count = node.count + 1
    
    def countSeq(self, sequence):
        '''计算序列出现的次数
        '''
        node = self.root
        for c in sequence:
            if c not in node.children:
                return 0
            else:
                node = node.children[c]
        return node.count
    
def gen_trie(input_file, output_file):
    '''生成trie树
    '''
    trie = Trie()
    
    with open(input_file) as f:
        for line in f:
            # 增加'$'用来区别是否是完整后缀
            line = line.strip() + '$'
            for i in range(len(line)):
                l = line[i:]
                trie.add(l)
            
    with open(output_file, 'wb') as f:
        pickle.dump(trie, f)
        
    return trie
  
if __name__ == '__main__':
    txt = 'data.txt'
    pkl = 'data.pkl'
    t = gen_trie(txt, pkl)

转载于:https://my.oschina.net/leopardsaga/blog/96727

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值