[英]Passing Trie tree node as parameter - not working
我正在嘗試實現一個功能,該功能讀取Trie樹中包含的所有單詞,將它們與鍵一起存儲在列表中,並將它們寫入.csv文件中。 函數“ insertTrie”工作正常; 但是,當我將“ root”作為參數傳遞給函數“ getAllTrie”時,由於某種原因,當我在函數中打印它(作為測試)時,它會向節點添加一個字符串(“ q”),然后顯示“ AttributeError” :'str'對象沒有屬性'char'”。 當我在函數外部打印“ root”時,字符串不存在。 是什么原因造成的? 我花了很長時間試圖找到答案。
import csv
class Node():
def __init__(self):
self.sons = {}
self.char = None
self.value = None
def insertTrie(currentNode, word, size):
if(size == len(word)):
if(currentNode.value is None):
currentNode.value = 1
else:
currentNode.value += 1
return currentNode
currentChar = word[size]
if(currentChar not in currentNode.sons):
currentNode.sons[currentChar] = Node()
currentNode.sons[currentChar].char = currentChar
currentNode.sons[currentChar] = insertTrie(currentNode.sons[ccurrentChar], word, size+1)
return currentNode
def getAllTrie(currentNode, findWord):
if(currentNode is not None):
#print(currentNode) -> print root inside function, 'q' appears
if(currentNode.char is not None):
if(findWord is None):
findWord = []
findWord.append(currentNode.char)
if(currentNode.value is not None):
wordAndKey = [''.join(findWord), currentNode.value]
writeCSVfile('exit.csv', wordAndKey) # writes word and key in csv file
findWord = None
for son in currentNode.sons:
getAllTrie(son, findWord)
root = Node()
testStr = 'querida queremos ate quero quero'
listStr = testStr.split( )
for word in listStr:
root = insertTrie(root, word, 0)
#print(root) -> print root outside of function, 'q' doesn't appear
getAllTrie(root, None)
當我在函數“ getAllTrie”(在代碼的注釋中)之外打印“ root”時,它打印以下內容:
<__main__.Node object at 0x03323610>
但是,當我將其打印在函數內部(也在注釋中)時,它會打印以下內容:
<__main__.Node object at 0x03323610>
q
我不知道為什么會有“ q”。 它是根的一個兒子中包含的字符,但是當我在函數中打印根本身時,它就會顯示出來,我也不知道為什么。
您的sons
屬性是一個dict,將單字符字符串映射到節點。
因此,當您這樣做時:
for son in currentNode.sons:
…每個son
都是一個單字符str
對象,而不是Node
對象。 這就是為什么第一個遞歸調用會打印出q
原因,並且為什么它會引發關於沒有sons
屬性的'q'
字符串的異常。
如果要遍歷字典中的值而不是鍵 ,則需要這樣說:
for son in currentNode.sons.values():
您的代碼中還有其他多個錯誤,從無效的縮進到ccurrentChar
拼寫錯誤,而且它是不完整的(任何地方都沒有writeCSVFile
函數),因此我無法測試這是否真的可以修復您的函數,但是可以解決此特定錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.