【问题标题】:NLTK draw tree in non-blocking wayNLTK 以非阻塞方式绘制树
【发布时间】:2020-01-22 12:04:18
【问题描述】:

NLTK 提供了一项功能,允许您“绘制”树结构,例如依赖解析。在实践中,当您调用tree.draw() 时,会弹出一个窗口(至少在 Windows 上)以及绘制的树。尽管这是一个不错的功能,但它也会阻塞,这意味着在绘制树时会阻塞脚本的执行,直到您关闭新绘制的树的窗口。

有没有办法以非阻塞方式绘制树,即不让它们停止脚本的执行?我曾考虑在 Python 中启动一个单独的进程来负责绘制树,但也许有更直接的方法。

【问题讨论】:

  • 使用更新方法的方法对您有用吗?
  • @DBaker 没有时间对其进行全面测试。我会及时通知你。

标签: python tree nltk nonblocking


【解决方案1】:

NLTK 使用 Tkinter 画布来显示树结构。 Tkinter 有一个 mainloop 方法,它可以等待事件并更新 GUI。但是这个方法是阻塞它之后的代码(更多关于这个herehere)。
我们可以使用非阻塞的 update 方法来代替 mainloop 方法。它更新 Tkinter 画布,然后返回。
下面是我们如何使用 NLTK 做到这一点:

import nltk
from nltk import pos_tag
pattern = """NP: {<DT>?<JJ>*<NN>}
... VBD: {<VBD>}
... IN: {<IN>}"""
NPChunker = nltk.RegexpParser(pattern)

sentences = ['the small dog is running',
             'the big cat is sleeping',
             'the green turtle is swimming'
            ]

def makeTree(sentence):
    tree = NPChunker.parse(pos_tag(sentence.split()))
    return(tree)

from nltk.draw.util import Canvas
from nltk.draw import TreeWidget
from nltk.draw.util import CanvasFrame

cf = CanvasFrame()

for sentence in sentences:
    tree = makeTree(sentence)
    tc = TreeWidget(cf.canvas(), tree)
    cf.add_widget(tc)
    cf.canvas().update()


## .. the rest of your code here
print('this code is non-blocking')

#at the end call this so that the programm doesn't terminate and close the window
cf.mainloop()

【讨论】:

  • 我刚才有时间测试了一下,确实是无阻塞的。但是,该窗口缺少一些功能,尤其是似乎无法移动树木。通常,您可以单击并拖动以移动树木。这很重要,因为对于较大的树,您现在有重叠。您认为可以添加这样的功能吗?
  • 我不知道该怎么做。 (我只阅读了足够多的 Tkinter 文档来了解它的阻塞与非阻塞方面)
猜你喜欢
  • 2015-03-31
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-12
  • 2020-10-08
相关资源
最近更新 更多