Python 将Trie树节点作为参数传递-不工作
我正在尝试实现一个函数,该函数读取Trie树中包含的所有单词,将它们与键一起存储在列表中,并将它们写入.csv文件中。函数“insertTrie”运行良好;但是,当我将'root'作为参数传递给函数'getAllTrie'时,由于某种原因,当我在函数中打印它时(作为测试),它会向节点添加一个字符串('q'),然后发生“AttributeError:'str'对象没有属性'char'。当我在函数外部打印“root”时,字符串不在那里。这是什么原因造成的?我花了很长时间试图找到答案Python 将Trie树节点作为参数传递-不工作,python,python-3.x,tree,trie,Python,Python 3.x,Tree,Trie,我正在尝试实现一个函数,该函数读取Trie树中包含的所有单词,将它们与键一起存储在列表中,并将它们写入.csv文件中。函数“insertTrie”运行良好;但是,当我将'root'作为参数传递给函数'getAllTrie'时,由于某种原因,当我在函数中打印它时(作为测试),它会向节点添加一个字符串('q'),然后发生“AttributeError:'str'对象没有属性'char'。当我在函数外部打印“root”时,字符串不在那里。这是什么原因造成的?我花了很长时间试图找到答案 import c
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
但当我在函数内部打印它时(也在注释中),它会打印以下内容:
<__main__.Node object at 0x03323610>
<__main__.Node object at 0x03323610>
q
Q
我不知道为什么会有“q”。它是根的一个子元素中包含的字符,但当我在函数中打印根元素时,它会显示出来,我不知道为什么。您的
子元素属性是dict,将单个字符串映射到节点
因此,当您这样做时:
for son in currentNode.sons:
…每个son
都是单个字符str
对象,而不是节点
对象。这就是为什么第一个递归调用打印出q
,以及为什么它引发了一个关于'q'
字符串没有sons
属性的异常
如果要迭代dict中的值,而不是键,则需要这样说:
for son in currentNode.sons.values():
您的代码中还存在多个其他错误,从无效缩进到像ccurrentChar
这样的打字错误,而且它不完整(任何地方都没有writeCSVFile
函数),因此我无法测试这是否真的修复了您的函数,但它确实修复了这个特定的错误。很抱歉输入错误,不包括writeCSVFile。这确实解决了问题,非常感谢。我还纠正了代码中的其他错误。