如何使iPython/Jupyter中内联的NLTK draw()树 [英] How do you make NLTK draw() trees that are inline in iPython/Jupyter

查看:177
本文介绍了如何使iPython/Jupyter中内联的NLTK draw()树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于iPython/Jupyter中的Matplotlib图,您可以使笔记本图以

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

%matplotlib inline

对于树的NLTK draw(),该怎么做?这是文档 http://www.nltk.org/api/nltk.draw.html

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

推荐答案

基于答案:

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类型的错误)

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 :似乎jupyter和nltk的最新版本可以很好地协同工作,因此您只需执行IPython.core.display.display(tree)即可将漂亮的树状渲染嵌入到输出中.

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.

这篇关于如何使iPython/Jupyter中内联的NLTK draw()树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆