[英]Storing word count in the python trie
我拿了一個單詞列表,把它放在一個特里。 我還想在里面存儲字數以供進一步分析。 最好的方法是什么? 這是我認為頻率將被收集和存儲的類,但我不知道如何去做。 你可以看到我的嘗試,插入中的最后一行是我嘗試存儲計數的地方。
class TrieNode:
def __init__(self,k):
self.v = 0
self.k = k
self.children = {}
def all_words(self, prefix):
if self.end:
yield prefix
for letter, child in self.children.items():
yield from child.all_words(prefix + letter)
class Trie:
def __init__(self):
self.root = TrieNode()
def __init__(self):
self.root = TrieNode()
def insert(self, word):
curr = self.root
for letter in word:
node = curr.children.get(letter)
if not node:
node = TrieNode()
curr.children[letter] = node
curr.v += 1
def insert_many(self, words):
for word in words:
self.insert(word)
def all_words_beginning_with_prefix(self, prefix):
cur = self.root
for c in prefix:
cur = cur.children.get(c)
if cur is None:
return # No words with given prefix
yield from cur.all_words(prefix)
我想存儲計數,以便在使用時
print(list(trie.all_words_beginning_with_prefix('prefix')))
我會得到這樣的結果:
[(word, count), (word, count)]
插入時,在看到任何節點時,這意味着將在該路徑中添加一個新詞。 因此,增加該節點的 word_count。
class TrieNode:
def __init__(self, char):
self.char = char
self.word_count = 0
self.children = {}
def all_words(self, prefix, path):
if len(self.children) == 0:
yield prefix + path
for letter, child in self.children.items():
yield from child.all_words(prefix, path + letter)
class Trie:
def __init__(self):
self.root = TrieNode('')
def insert(self, word):
curr = self.root
for letter in word:
node = curr.children.get(letter)
if node is None:
node = TrieNode(letter)
curr.children[letter] = node
curr.word_count += 1 # increment it everytime the node is seen at particular level.
curr = node
def insert_many(self, words):
for word in words:
self.insert(word)
def all_words_beginning_with_prefix(self, prefix):
cur = self.root
for c in prefix:
cur = cur.children.get(c)
if cur is None:
return # No words with given prefix
yield from cur.all_words(prefix, path="")
def word_count(self, prefix):
cur = self.root
for c in prefix:
cur = cur.children.get(c)
if cur is None:
return 0
return cur.word_count
trie = Trie()
trie.insert_many(["hello", "hi", "random", "heap"])
prefix = "he"
words = [w for w in trie.all_words_beginning_with_prefix(prefix)]
print("Lazy method:\n Prefix: %s, Words: %s, Count: %d" % (prefix, words, len(words)))
print("Proactive method:\n Word count for '%s': %d" % (prefix, trie.word_count(prefix)))
輸出:
Lazy method:
Prefix: he, Words: ['hello', 'heap'], Count: 2
Proactive method:
Word count for 'he': 2
我會向 trie 節點添加一個名為 is_word 的字段,其中 is_word 僅對單詞中的最后一個字母為真。 就像你有單詞 AND 一樣,對於包含字母 D 的 trie 節點,is_word 將是真的。我只會更新具有 is_word 的節點的頻率,而不是單詞中的每個字母。
所以當你從一個字母迭代時,檢查它是否是一個單詞,如果是,停止迭代,返回計數和單詞。 我假設在您的迭代中您會跟蹤這些字母,並不斷將它們添加到前綴中。
你的特里是一個多路特里。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.