简体   繁体   中英

How to save a dependency graph as image in NLTK Python

I found a few posts including this one on how to generate a dependency graph. However, I'm looking for an option to export a dependency graph as a PNG/SVG image.

For simplicity, let's assume we already parsed a sentence The quick brown fox jumps over the lazy dog. and we have the output in to_conll(4) format. Now if pass this result to the DependencyGrpah class

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

It produces the following the image

nltk中的依赖图

My question is how can I save this image as a PNG/SVG file?

You can convert it from a .ps to 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')

If you are using VScode to experiment with notebook files, there is a small icon at the right upper corner. then there will be an icon in the right upper corner to save your graph.

You can use the method to_dot() on your DataGraph object, and then proceed to create a Graphviz object from raw and then save it into a file with render .

You can choose both the filename and the format (png, pdf...), as reported in the method signature

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM