Saving nltk drawn parse tree to image file

大城市里の小女人 提交于 2019-11-26 17:46:24

问题


Is there any way to save the draw image from tree.draw() to an image file programmatically? I tried looking through the documentation, but I couldn't find anything.


回答1:


I had exactly the same need, and looking into the source code of nltk.draw.tree I found a solution:

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

The output file is a postscript, and you can convert it to an image file using ImageMagick on terminal:

$ convert tree.ps tree.png

I think this is a quick and dirty solution; it could be inefficient in that it displays the canvas and destroys it later (perhaps there is an option to disable display, which I couldn't find). Please let me know if there is any better way.




回答2:


Using the nltk.draw.tree.TreeView object to create the canvas frame automatically:

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

Then:

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

[output.png]:




回答3:


To add to Minjoon's answer, you can change the fonts and colours of the tree to look more like the NLTK .draw() version as follows:

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

Before (left) and after (right):



来源:https://stackoverflow.com/questions/23429117/saving-nltk-drawn-parse-tree-to-image-file

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