How to save a dependency graph as image in NLTK Python

Viewed 400

I found a few posts including this one on how to generate a dependency graph. However, I'm looking for an option to export a dependency graph as a PNG/SVG image.

For simplicity, let's assume we already parsed a sentence The quick brown fox jumps over the lazy dog. and we have the output in to_conll(4) format. Now if pass this result to the DependencyGrpah class

from nltk.parse import DependencyGraph
DependencyGraph(
'''The  DT  4   det
quick   JJ  4   amod
brown   JJ  4   amod
fox NN  5   nsubj
jumps   VBZ 0   ROOT
over    IN  9   case
the DT  9   det
lazy    JJ  9   amod
dog NN  5   obl
.   .   5   punct'''
)

It produces the following the image

dependency graph in nltk

My question is how can I save this image as a PNG/SVG file?

3 Answers

You can convert it from a .ps to a .png.

import os
from nltk.draw.tree import TreeView

TreeView(GRAPH)._cframe.print_to_file('tree.ps')
os.system('convert tree.ps tree.png')

If you are using VScode to experiment with notebook files, there is a small icon at the right upper corner. then there will be an icon in the right upper corner to save your graph.

Related