Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make NLTK draw() trees that are inline in iPython/Jupyter

For Matplotlib plots in iPython/Jupyter you can make the notebook plot plots inline with

%matplotlib inline

How can one do the same for NLTK draw() for trees? Here is the documentation http://www.nltk.org/api/nltk.draw.html

like image 726
mikal94305 Avatar asked Aug 03 '15 05:08

mikal94305


2 Answers

Based on this answer:

import os
from IPython.display import Image, display
from nltk.draw import TreeWidget
from nltk.draw.util import CanvasFrame

def jupyter_draw_nltk_tree(tree):
    cf = CanvasFrame()
    tc = TreeWidget(cf.canvas(), tree)
    tc['node_font'] = 'arial 13 bold'
    tc['leaf_font'] = 'arial 14'
    tc['node_color'] = '#005990'
    tc['leaf_color'] = '#3F8F57'
    tc['line_color'] = '#175252'
    cf.add_widget(tc, 10, 10)
    cf.print_to_file('tmp_tree_output.ps')
    cf.destroy()
    os.system('convert tmp_tree_output.ps tmp_tree_output.png')
    display(Image(filename='tmp_tree_output.png'))
    os.system('rm tmp_tree_output.ps tmp_tree_output.png')

Little slow, but does the job. If you're doing it remotely, don't forget to run your ssh session with -X key (like ssh -X [email protected]) so that Tk could initialize itself (no display name and no $DISPLAY environment variable-kind of error)

UPD: it seems like last versions of jupyter and nltk work nicely together, so you can just do IPython.core.display.display(tree) to get a nice-looking tree-render embedded into the output.

like image 50
Ben Usman Avatar answered Oct 11 '22 21:10

Ben Usman


2019 Update:

This runs on Jupyter Notebook:

from nltk.tree import Tree
from IPython.display import display

tree = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
display(tree)

Requirements:

  • NLTK
  • Ghostscript
like image 35
Eric McLachlan Avatar answered Oct 11 '22 21:10

Eric McLachlan