Saving nltk drawn parse tree to image file

John picture John · May 2, 2014 · Viewed 11.1k times · Source

enter image description here

Is there any way to save the draw image from tree.draw() to an image file programmatically? I tried looking through the documentation, but I couldn't find anything.

Answer

alvas picture alvas · Jan 31, 2016

Using the nltk.draw.tree.TreeView object to create the canvas frame automatically:

>>> from nltk.tree import Tree
>>> from nltk.draw.tree import TreeView
>>> t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
>>> TreeView(t)._cframe.print_to_file('output.ps')

Then:

>>> import os
>>> os.system('convert output.ps output.png')

[output.png]:

enter image description here