NLTK提供了一项功能,可让您“绘制”树状结构,例如依赖项解析。实际上,当您调用tree.draw()
时,绘制的树会弹出一个窗口(至少在Windows上是)。即使这是不错的功能,它也会阻塞,这意味着在绘制树时将阻止脚本的执行,直到关闭新绘制的树的窗口为止。
是否有任何非阻塞方式绘制树的方法,即没有树停止脚本的执行?我曾考虑过要在Python中启动一个单独的过程来负责绘制树,但也许有更直接的方法。
NLTK使用Tkinter画布显示树结构。Tkinter具有mainloop方法,该方法使其等待事件并更新GUI。但是此方法将阻止其后的代码(有关here和here的更多信息)。代替mainloop方法,我们可以使用非阻塞的update方法。它更新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()