使用svgling模块,我生成了选区解析树。以下是svgling:svgling模块github的github链接
pip install svgling
import svgling
import nltk
var ='(S (NP this tree) (VP (V is) (AdjP pretty)))'
svgling.disable_nltk_png()
random=svgling.draw_tree(nltk.Tree.fromstring(var))
display(random)
使用这段代码,我得到了这个图作为选区解析树的输出(如下所示)。我想要生成这个输出的.png文件。选区解析树(上述代码的输出)
为了将输出保存为.png文件,我运行了以下代码。
import os
from nltk.tree import Tree
from nltk.draw.tree import TreeView
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
os.system('Xvfb :1 -screen 0 1600x1200x16 &') # create virtual display with size 1600x1200 and 16 bit color. Color can be changed to 24 or 8
os.environ['DISPLAY']=':1.0'
t = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP pretty)))')
cf = CanvasFrame()
TreeView(t)._cframe.print_to_file('output.ps')
os.system('convert output.ps output.png')
然而,这段代码在google TclError: couldn't connect to display ":1.0"
中显示了错误,并在jupyter笔记本中返回了一个数值(ex: 4)。
我试图在几个网站上调查它,但没有找到任何解决办法。
发布于 2022-03-15 09:06:40
有一次,我还必须将选区解析图转换为图像。为此,我首先将其转换为PostScript (.ps)文件。然后,从.ps文件将其转换为.png文件。
为了将树关系图转换为.ps文件,我运行了以下代码。这将给出output.ps文件。
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')
然而,我试图在google上运行代码。它给出了一个错误:
TclError: Google中没有显示名称和$DISPLAY环境变量
若要解决此问题,请运行以下代码:
!apt-get install -y xvfb # Install X Virtual Frame Buffer
import os
os.system('Xvfb :1 -screen 0 1600x1200x16 &') # create virtual display with size 1600x1200 and 16 bit color. Color can be changed to 24 or 8
os.environ['DISPLAY']=':1.0'
现在要将output.ps文件转换为output.png:
!apt install ghostscript python3-tk
from PIL import Image
psimage=Image.open('output.ps')
psimage.save('output.png')
然而,这样无法获得很好的图像质量。
https://stackoverflow.com/questions/71481565
复制