将 nltk 绘制的解析树保存到图像文件 [英] Saving nltk drawn parse tree to image file

查看:28
本文介绍了将 nltk 绘制的解析树保存到图像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法以编程方式将 tree.draw() 中的绘图图像保存到图像文件中?我尝试查看文档,但找不到任何内容.

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.

推荐答案

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

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

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

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.

这篇关于将 nltk 绘制的解析树保存到图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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