我正在尝试在NLTK树上进行广度优先遍历。但是在当前节点上调用子树方法时,它不会给我子树,而是现有节点本身。
def traverseTree(tree):
queue = [tree]
visited = set(tree.label())
while queue:
node = queue.pop(0)
for neighbor in node.subtrees():
if neighbor.label() not in visited:
queue.append(neighbor)
visited.add(neighbor.label())
return visited
任何人都可以告诉nltk树上的bfs怎么做?
def bfs(tree, children=iter, maxdepth=-1):
queue = deque([(tree, 0)])
while queue:
node, depth = queue.popleft()
yield node
if depth != maxdepth:
try:
queue.extend((c, depth + 1) for c in children(node))
except TypeError:
pass
即使将其添加到我的代码中,我也无法调用此默认bfs实现。