How do you make NLTK draw() trees that are inline in iPython/Jupyter
对于 iPython/Jupyter 中的 Matplotlib 绘图,您可以将笔记本绘图与
内联
1 | %matplotlib inline |
如何为树的 NLTK draw() 做同样的事情?这是文档 http://www.nltk.org/api/nltk.draw.html
基于这个答案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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') |
有点慢,但可以。如果您是远程操作,请不要忘记使用
UPD:似乎最新版本的 jupyter 和 nltk 可以很好地协同工作,因此您只需执行
2019 年更新:
这在 Jupyter Notebook 上运行:
1 2 3 4 5 | from nltk.tree import Tree from IPython.display import display tree = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))') display(tree) |
要求:
- NLTK
- 鬼脚本