【问题标题】:Saving nltk graphs to file on a headless server/virtual machine将 nltk 图保存到无头服务器/虚拟机上的文件
【发布时间】:2016-11-07 18:15:38
【问题描述】:

取自Saving nltk drawn parse tree to image file

我想知道在使用无头虚拟机/服务器时如何保存图像?现在我得到:

_tkinter.TclError: 没有显示名称和 $DISPLAY 环境变量

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

【问题讨论】:

    标签: python matplotlib virtual-machine nltk headless


    【解决方案1】:

    因此,经过大量探索和试验大量库和将 nltk 解析树从字符串获取到最终图像的方法后,以下对我有用:

    要安装的依赖项:

    1. nltk - 从字符串中读取一棵树并解析它(就像你所做的那样)。
    2. svgling - 这个库可以读取 nltk 树的输出并将其转换为 svg。
    3. cairosvg - 这个库读取 svg 并可以将其转换为 png、pdf 等格式的任何内容。它不依赖于 tcl/tkinter,因此无头服务器没有问题!

    带有示例树的代码:

    import svgling
    import cairosvg
    from nltk.tree import Tree
    
    # converts any nltk tree object to a svg
    def tree2svg(t):
        img = svgling.draw_tree(t)
        svg_data = img.get_svg()
        return svg_data
    
    # read from a string and parse the tree using nltk
    t = Tree.fromstring('(ROOT (S (NP (DT The) (NN debate)) (VP (VBN continued) (PP (IN till) (NP (NN night)))) (. .)))')
    # convert tree to svg
    sv = tree2svg(t)
    # write the svg as an image
    cairosvg.svg2png(sv.tostring(), write_to='image.png')
    

    上述代码在 Windows 10 内的 ubuntu wsl 上完美运行,因此它也适用于任何服务器(因为我面临与您完全相同的问题)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多