ddb*_*eck 3 python parsing list
假设我有一个这样的项目符号列表:
* list item 1
* list item 2 (a parent)
** list item 3 (a child of list item 2)
** list item 4 (a child of list item 2 as well)
*** list item 5 (a child of list item 4 and a grand-child of list item 2)
* list item 6
Run Code Online (Sandbox Code Playgroud)
我想将其解析为嵌套列表或其他一些数据结构,这使得元素之间的父子关系显式化(而不是依赖于它们的内容和相对位置).例如,这是一个元组列表,其中包含一个项目及其子项列表(等等):
编辑:希望是一个更正确的列表示例,其中列表中的每个元素都是一个元组,其中包含:子弹的文本以及子项列表(如果适用)(以相同的形式).
[('list item 1',),
('list item 2', [('list item 3',), ('list item 4', [('list item 5',)])]
('list item 6',)]
[('list item 1',),
('list item 2', [('list item 3',), ('list item 4', [('list item 5',)])]),
('list item 6',)]
Run Code Online (Sandbox Code Playgroud)
我试图用普通的Python和一些Pyparsing的实验做到这一点,但我没有取得进展.我有两个主要问题:
在搜索算法的视图中,您提供的子弹实际上是由Depth-First-Search生成的序列.所以我的策略是用dfs-sequence重建树结构.
以下是python代码:
from collections import deque
def dfsBullet(bullet,depth):
"""
parse the subtree with depth and the startnode of bullet[0]
"""
li = []
if depth != 0:
item = bullet.popleft()
li.append(item.split(' ',1)[1])
while (len(bullet) != 0):
item = bullet[0]
#apply same algo to the child node
if len(item.split(' ',1)[0]) > depth:
sublist = dfsBullet(bullet, len(item.split(' ')[0]))
#we have traverse all childnode, so go back
else:
return li
#add child tree to the list
li.append(sublist)
return li
Run Code Online (Sandbox Code Playgroud)