可视化解析树 - Python 中嵌套列表转换为树形结构

3

我拥有一个CYK解析的输出,它是一个嵌套的列表:

parser.parse('the dog saw the man with the telescope')

Out :
["S", ["NP", ["DT", "the"], ["NN", "dog"]], ["VP", ["Vt", "saw"], ["NP", ["NP", ["DT", "the"], ["NN", "man"]], ["PP", ["P", "with"], ["NP", ["DT", "the"], ["NN", "telescope"]]]]]]

请问如何将这个嵌套列表转换成易于解释的树形结构?类似于这样:

enter image description here

我该如何在Python或使用其他外部库中实现它?能有人帮帮我吗?


["NN", "dog"]应该发生什么? - Dani Mesejo
是的,我想要一个完整的解析树可视化,从顶部的POS标签到叶节点中的单词。我在问题中只给了一个小例子。 - AnonymousMe
是的,但它们如何适应树形结构? - Dani Mesejo
我已经编辑了我的问题并展示了一个例子。谢谢! - AnonymousMe
1个回答

2

我会这样使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接