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

六月ゝ 毕业季﹏ 提交于 2019-12-08 19:14:25

问题


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


回答1:


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 user@server.com) 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.




回答2:


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)))')
IPython.core.display.display(tree)

Requirements:

  • NLTK
  • Ghostscript


来源:https://stackoverflow.com/questions/31779707/how-do-you-make-nltk-draw-trees-that-are-inline-in-ipython-jupyter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!