Reputation: 569
I have the output of CYK Parsing as a nested list :
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"]]]]]]
Could someone please tell me how to convert this nested list into a Tree that can be easily interpreted ? Something like this :
How do I achieve this in Python or using any other external libraries ? Could someone please help me ?
Upvotes: 3
Views: 1507
Reputation: 61920
I would use treelib, in the following fashion:
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()
Output
S
├── NP
│ ├── DT
│ │ └── the
│ └── NN
│ └── dog
└── VP
├── NP
│ ├── NP
│ │ ├── DT
│ │ │ └── the
│ │ └── NN
│ │ └── man
│ └── PP
│ ├── NP
│ │ ├── DT
│ │ │ └── the
│ │ └── NN
│ │ └── telescope
│ └── P
│ └── with
└── Vt
└── saw
Upvotes: 2