Trie树实现词频统计与查找
2017-01-15 14:56
288 查看
#encoding:utf-8 from collections import defaultdict import sys reload(sys) sys.setdefaultencoding('utf8') class LBTrie: """ simple implemention of Trie in Python. """ def __init__(self): self.trie = {} self.size = 0 #添加单词 def add(self, word): p = self.trie dicnum = 0 word = word.strip() for c in word: if not c in p: p[c] = {} dicnum+=1 p = p[c] if word != '': #在单词末尾处添加键值''作为标记,即只要某个字符的字典中含有''键即为单词结尾 p[''] = '' if dicnum == len(word): return True #查询单词 def search(self, word): p = self.trie word = word.lstrip() for c in word: if not c in p: return False p = p[c] #判断单词结束标记'' if '' in p: return True return False #打印Trie树的接口 def output(self): #print '{' self.__print_item(self.trie) #print '}' return self.__print_item(self.trie) #实现Trie树打印的私有递归函数,indent控制缩进 def __print_item(self, p, indent=0): if p: ind = '' + '\t' * indent for key in p.keys(): label = "'%s' : " % key print ind + label + '{' self.__print_item(p[key], indent+1) print ind + ' '*len(label) + '}' def codeutil(strs): return strs.decode('utf8','ignore').encode('GBK','ignore').decode('GBK','ignore') if __name__ == '__main__': trie_obj = LBTrie() #添加单词 corpus = open('content.txt','r') tree = open('tree.txt','w+') countdic = defaultdict(int) for record in corpus.readlines(): recordlist = record.split(' ') for word in recordlist: check = trie_obj.add(codeutil(word)) if check: countdic[word] += 1 resortedcountdic = sorted(countdic.items(), key=lambda item: item[1], reverse=True) for tup in resortedcountdic: tree.write(''.join(codeutil(tup[0]))+'\t'+str(tup[1])+'\t') #查找单词 if trie_obj.search(codeutil('氨基酸')): print 'Yes' else: print 'No'
相关文章推荐
- Trie树(字典树)实现词频统计或前缀匹配类型的问题
- 字典树(trie树)实现词频查找
- 用Trie树实现词频统计和单词查询
- Trie树:统计词频、排序、查找
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- java实现查找统计文本文件
- Trie树词频统计实例
- C下学生管理系统:从文件中读取30位学生的信息(含邮箱),并实现简单的增、删、查找、统计(邮箱使用人数)。---附程序哦!
- 二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- LeetCode Implement Trie (Prefix Tree) (实现trie树3个函数:插入,查找,前缀)
- python下学生管理系统:从文件中读取30位学生的信息(含邮箱),并实现简单的增、删、查找、统计(邮箱使用人数)。---附程序哦!
- C语言实现英文文本词频统计
- Hadoop 2.2.0词频统计(实现自定义的Partitioner和Combiner)
- 软件工程-关于词频统计程序设计实现分析
- Hihocoder #1014 : Trie树 (字典数树统计前缀的出现次数 *【模板】 基于指针结构体实现 )
- 用非递归实现二叉树的前序、中序、后序、层次遍历,用递归实现查找、统计个数、比较、求深度
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- Java实现的一个词频统计程序
- 字典树-大量字符串前缀及出现次数是否存在统计(Trie树-java)算法实现