如何在 NLTK Python 中将依赖图保存为图像

问题描述

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

为简单起见,我们假设我们已经解析了一个句子 degree value smoothed 0 0.0 0.421053 0.457895 1 1.0 0.473684 0.450000 2 2.0 0.473684 0.450000 3 3.0 0.473684 0.450000 4 4.0 0.500000 0.452632 5 5.0 0.500000 0.457895 6 6.0 0.500000 0.463158 7 7.0 0.473684 0.465789 8 8.0 0.473684 0.471053 9 9.0 0.473684 0.476316 10 10.0 0.394737 0.473684 .... .... 并且我们有 to_conll(4) 格式的输出。现在,如果将此结果传递给 The quick brown fox jumps over the lazy dog.

DependencyGrpah

它产生以下图像

dependency graph in nltk

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

解决方法

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

import os
from nltk.draw.tree import TreeView

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

如果你使用 VScode 来试验 notebook 文件,右上角会有一个小图标。然后右上角会有一个图标来保存你的图表。

,

您可以在 DataGraph 对象上使用 to_dot() 方法,然后继续执行 create a Graphviz object from raw,然后将其保存到带有 render 的文件中。

您可以选择文件名和格式(png、pdf...),如 method signature