将nltk绘制的解析树保存到图像文件

时间:2014-05-02 13:16:56

标签: python tree nlp nltk text-parsing

enter image description here

有没有办法以编程方式将绘图图像从tree.draw()保存到图像文件?我试着查看文档,但我找不到任何东西。

3 个答案:

答案 0 :(得分:11)

我有完全相同的需求,并查看nltk.draw.tree的源代码我找到了解决方案:

from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget

cf = CanvasFrame()
t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()

输出文件是postscript,您可以使用终端上的ImageMagick将其转换为图像文件:

$ convert tree.ps tree.png

我认为这是一个快速而肮脏的解决方案;它可能是低效的,因为它显示画布并在以后销毁它(也许有一个选项来禁用显示,我找不到)。如果有更好的方法,请告诉我。

答案 1 :(得分:11)

使用nltk.draw.tree.TreeView对象自动创建画布框:

>>> from nltk.tree import Tree
>>> from nltk.draw.tree import TreeView
>>> t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
>>> TreeView(t)._cframe.print_to_file('output.ps')

然后:

>>> import os
>>> os.system('convert output.ps output.png')

[output.png]:

enter image description here

答案 2 :(得分:5)

要添加Minjoon的答案,您可以更改树的字体和颜色,使其看起来更像NLTK .draw()版本,如下所示:

tc['node_font'] = 'arial 14 bold'
tc['leaf_font'] = 'arial 14'
tc['node_color'] = '#005990'
tc['leaf_color'] = '#3F8F57'
tc['line_color'] = '#175252'

之前(左)和之后(右):

before after