简体   繁体   English

将Trie树节点作为参数传递-不起作用

[英]Passing Trie tree node as parameter - not working

I'm trying to implement a function that reads all words contained in a Trie tree, stores them in a list with their keys and writes them in a .csv file. 我正在尝试实现一个功能,该功能读取Trie树中包含的所有单词,将它们与键一起存储在列表中,并将它们写入.csv文件中。 The function 'insertTrie' works fine; 函数“ insertTrie”工作正常; however, when I pass 'root' as an argument to the function 'getAllTrie', for some reason it adds a string ('q') to the node when I print it within the function (as a test) and then the "AttributeError: 'str' object has no attribute 'char'" happens. 但是,当我将“ root”作为参数传递给函数“ getAllTrie”时,由于某种原因,当我在函数中打印它(作为测试)时,它会向节点添加一个字符串(“ q”),然后显示“ AttributeError” :'str'对象没有属性'char'”。 When I print 'root' outside the function, the string is not there. 当我在函数外部打印“ root”时,字符串不存在。 What is causing this? 是什么原因造成的? I've spent a long time trying to find the answer. 我花了很长时间试图找到答案。

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)

When I print the 'root' outside the function 'getAllTrie' (in commentary in the code), it prints this: 当我在函数“ getAllTrie”(在代码的注释中)之外打印“ root”时,它打印以下内容:

<__main__.Node object at 0x03323610>

But when I print it inside the function (also in commentary), it prints this: 但是,当我将其打印在函数内部(也在注释中)时,它会打印以下内容:

<__main__.Node object at 0x03323610>
q

I have no idea why that 'q' is there. 我不知道为什么会有“ q”。 It's the character contained in one of the root's sons, but it shows when I print the root itself in the function, and I have no idea why. 它是根的一个儿子中包含的字符,但是当我在函数中打印根本身时,它就会显示出来,我也不知道为什么。

Your sons attribute is a dict, mapping single-character strings to nodes. 您的sons属性是一个dict,将单字符字符串映射到节点。

So, when you do this: 因此,当您这样做时:

for son in currentNode.sons:

… each son is a single-character str object, not a Node object. …每个son都是一个单字符str对象,而不是Node对象。 That's why the first recursive call prints out q , and why it raises an exception about that 'q' string not having a sons attribute. 这就是为什么第一个递归调用会打印出q原因,并且为什么它会引发关于没有sons属性的'q'字符串的异常。

If you want to iterate over the values in a dict, rather than the keys , you need to say so: 如果要遍历字典中的而不是 ,则需要这样说:

for son in currentNode.sons.values():

You have multiple other errors in your code, from invalid indentation to typos like ccurrentChar , and it's incomplete (there's no writeCSVFile function anywhere), so I can't test whether this actually fixes your function—but it does fix this particular bug. 您的代码中还有其他多个错误,从无效的缩进到ccurrentChar拼写错误,而且它是不完整的(任何地方都没有writeCSVFile函数),因此我无法测试这是否真的可以修复您的函数,但是可以解决此特定错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM