如何制作在iPython / Jupyter中内联的NLTK draw()树

时间:2015-08-03 05:01:11

标签: ipython draw nltk jupyter

对于iPython / Jupyter中的Matplotlib图,您可以将笔记本图绘制为内嵌

%matplotlib inline

如何为树的NLTK draw()做同样的事情?这是文档http://www.nltk.org/api/nltk.draw.html

2 个答案:

答案 0 :(得分:8)

基于this回答:

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')

有点慢,但做的工作。如果您是远程执行此操作,请不要忘记使用-X密钥(例如ssh -X user@server.com)运行ssh会话,以便Tk可以自行初始化(no display name and no $DISPLAY environment variable - 出现错误)< / p>

UPD :看起来jupyter和nltk的最新版本可以很好地协同工作,所以你可以只做IPython.core.display.display(tree)来获得一个漂亮的树形渲染嵌入到输出中。

答案 1 :(得分:0)

2019更新:

它在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)

要求:

  • NLTK
  • Ghostscript