如何解决LXML 文件的广度优先搜索遍历 Python
我正在对 XML 文件执行广度优先搜索 (BFS) 遍历。 https://lxml.de/3.3/api.html#lxml-etre 中显示了深度优先搜索算法。但是,我需要基于此代码应用 BFS 搜索的帮助。 以下是文档中给出的代码:
>>> root = etree.XML('<root><a><b/><c/></a><d><e/></d></root>')
>>> print(etree.tostring(root,pretty_print=True,encoding='unicode'))
<root>
<a>
<b/>
<c/>
</a>
<d>
<e/>
</d>
</root>
>>> queue = deque([root])
>>> while queue:
... el = queue.popleft() # pop next element
... queue.extend(el) # append its children
... print(el.tag)
根 一种 d 乙 C
我需要帮助尝试附加它以使其适合 BFS 遍历。下面是我尝试编写但无法正常工作的代码示例。有人可以帮忙吗。 我的代码: 从集合导入双端队列
>>> d = deque([root])
>>> while d:
>>> el = d.pop()
>>> d.extend(el)
>>> print(el.tag)
谢谢
解决方法
您的 BFS 实现当前从队列的错误端弹出。您应该使用 popleft() 而不是 pop()。
d = deque([root])
while d:
el = d.popleft()
d.extend(el)
print(el.tag)
,
也可以用 xpath 实现
>>> root = etree.XML('<root><a><b/><c><f/></c></a><d><e/></d></root>')
>>> queue = deque([root])
>>> while queue:
... el = queue.popleft()
... queue.extend(el.xpath('./child::*'))
... print(el.tag)
...
root
a
d
b
c
e
f
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。