我会这样使用treelib:
from treelib import Node, Tree
lst = ["S", ["NP", ["DT", "the"], ["NN", "dog"]], ["VP", ["Vt", "saw"], ["NP", ["NP", ["DT", "the"], ["NN", "man"]],
["PP", ["P", "with"],
["NP", ["DT", "the"], ["NN", "telescope"]]]]]]
root, *tail = lst
tree = Tree()
node = Node(root)
tree.add_node(node)
q = [[node, *tail]]
while q:
parent, *children = q.pop()
for child in children:
if isinstance(child, list):
head, *tail = child
node = tree.create_node(head, parent=parent)
q.append([node, *tail])
else:
tree.create_node(child, parent=parent)
tree.show()
输出
S
├── NP
│ ├── DT
│ │ └── the
│ └── NN
│ └── dog
└── VP
├── NP
│ ├── NP
│ │ ├── DT
│ │ │ └── the
│ │ └── NN
│ │ └── man
│ └── PP
│ ├── NP
│ │ ├── DT
│ │ │ └── the
│ │ └── NN
│ │ └── telescope
│ └── P
│ └── with
└── Vt
└── saw
["NN", "dog"]
应该发生什么? - Dani Mesejo