Findall() search functionality in python library 'anytree' returns NameError: 'findall' is not defined

Findall() search functionality in python library 'anytree' returns NameError: 'findall' is not defined

我将 python 中的 anytree 库用于我正在处理的项目,该项目利用了该库的树功能。我希望能够在树中进行搜索,但是文档中显示的搜索命令不起作用。

这是直接来自此处文档的示例树:https://anytree.readthedocs.io/en/latest/api/anytree.search.html#anytree.search.findall

>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> print(RenderTree(f, style=AsciiStyle()).by_attr())
f
|-- b
|   |-- a
|   +-- d
|       |-- c
|       +-- e
+-- g
    +-- i
        +-- h
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
(Node('/f/b'), Node('/f/b/a'))
>>> findall(f, filter_=lambda node: d in node.path)
(Node('/f/b/d'), Node('/f/b/d/c'), Node('/f/b/d/e'))

当我在 IDLE 中复制这段代码时,我得到了这个错误:

>>> from anytree import Node, RenderTree, AsciiStyle
>>> f = Node("f")
>>> b = Node("b", parent=f)
>>> a = Node("a", parent=b)
>>> d = Node("d", parent=b)
>>> c = Node("c", parent=d)
>>> e = Node("e", parent=d)
>>> g = Node("g", parent=f)
>>> i = Node("i", parent=g)
>>> h = Node("h", parent=i)
>>> findall(f, filter_=lambda node: node.name in ("a", "b"))
Traceback (most recent call last):
  File "<pyshell#16>", line 1, in <module>
    findall(f, filter_=lambda node: node.name in ("a", "b"))
NameError: name 'findall' is not defined

如果我需要导入其他东西,或者是否有任何其他方法可以使用 anytree 搜索树,请告诉我。

您还没有导入该函数。一个解决方案可能是为该函数添加一个导入

from anytree import Node, RenderTree, AsciiStyle, findall

或者您可以使用

从该模块导入所有内容
from anytree import *
f = Node("f")
findall(f, ...)

或者您可以像这样导入模块,但是您需要在该模块的所有内容前面添加 anytree.

import anytree
f = anytree.Node("f")
anytree.findall(f)

您必须导入搜索模块

from anytree import Node, RenderTree, AsciiStyle, search

result = search.findall(f, filter_=lambda node: node.name in ("a", "b"))

print(result) // (Node('/f/b'), Node('/f/b/a')