首页 > 解决方案 > 如何在 NLTK Python 中将依赖图保存为图像

问题描述

我发现了一些帖子,包括这篇关于如何生成依赖图的帖子。但是,我正在寻找将依赖关系图导出为 PNG/SVG 图像的选项。

为简单起见,假设我们已经解析了一个句子The quick brown fox jumps over the lazy dog.,并且我们有to_conll(4)格式的输出。现在如果将此结果传递给DependencyGrpah班级

from nltk.parse import DependencyGraph
DependencyGraph(
'''The  DT  4   det
quick   JJ  4   amod
brown   JJ  4   amod
fox NN  5   nsubj
jumps   VBZ 0   ROOT
over    IN  9   case
the DT  9   det
lazy    JJ  9   amod
dog NN  5   obl
.   .   5   punct'''
)

它产生以下图像

nltk中的依赖图

我的问题是如何将此图像保存为 PNG/SVG 文件?

标签: pythonnltkdependency-graph

解决方案


您可以将其从 a 转换.ps为 a .png

import os
from nltk.draw.tree import TreeView

TreeView(GRAPH)._cframe.print_to_file('tree.ps')
os.system('convert tree.ps tree.png')

推荐阅读