#encoding:utf-8
from collections import defaultdict
import sys
reload(sys)
sys.setdefaultencoding('utf8')
class
lbtrie:
"""
****** implemention of trie in python.
"""def__init__
(self):
self.trie = {}
self.size = 0
#新增單詞
defadd
(self, word):
p = self.trie
dicnum = 0
word = word.strip()
for c in word:
ifnot c in p:
p[c] = {}
dicnum+=1
p = p[c]
if word != '':
#在單詞末尾處新增鍵值''作為標記,即只要某個字元的字典中含有''鍵即為單詞結尾
p[''] = ''
if dicnum == len(word):
return
true
#查詢單詞
defsearch
(self, word):
p = self.trie
word = word.lstrip()
for c in word:
ifnot c in p:
return
false
p = p[c]
#判斷單詞結束標記''
if''
in p:
return
true
return
false
#列印trie樹的介面
defoutput
(self):
#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 + ''
defcodeutil
(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('氨基酸')):
'yes'
else:
'no'
trie樹 單詞樹 實現敏感詞遮蔽和詞頻統計
三 實現 前幾天都看乙個敏感詞遮蔽演算法的文章,寫的挺好,順著思路寫了下去,實現了一下,演算法效率還是槓槓的。利用的是單詞樹的演算法,先看看什麼叫單詞樹。單詞樹也叫trie 樹也稱為字典樹。最大的特點就是共享字串的公共字首來達到節省空間的目的。例如,字串 abc 和 abd 構成的單詞樹如下 樹的根...
Trie樹應用 統計與匹配
trie樹,是一種樹形結構,是一種雜湊樹的變種。典型應用是用於統計,排序和儲存大量的字串 但不僅限於字串 所以經常被搜尋引擎系統用於文字詞頻統計。它的優點是 利用字串的公共字首來減少查詢時間,最大限度地減少無謂的字串比較,查詢效率比雜湊表高。trie樹的基本特徵 1 根節點不包含字元,除根節點外每乙...
trie字母查詢樹java實現
1 實現單詞插入並統計插入次數 2 實現查詢單詞是否存於字母查詢樹中 3 實現自動補全提醒 注意 1 只支援全小寫字母單詞 2 查詢時間複雜度為log h h為單詞長度 3 插入時間複雜度為log h h為單詞長度 4 空間複雜度小於所有字母個數 結點 package bin.tree.trie 字...