使用tkinter在jupyter笔记本内部绘制nltk

我试图绘制jupyter-notebook内的jupyter-notebookgraphics( 内联 )。 但有错误:

 TclError: no display name and no $DISPLAY environment variable 

我试图将$DISPLAY设置$DISPLAY不同的值:

 $env DISPLAY=0.0 # or $env DISPLAY=inline # or $env DISPLAY= 

但有错误(或类似):

 TclError: couldn't connect to display "0.0" 

这里是我的代码https://github.com/hyzhak/nltk-experiments/blob/master/main.ipynb最后一个单元格。

环境:官方anaconda3docker – continuumio/anaconda3:4.4.0 https://github.com/ContinuumIO/docker-images 。 用nltk==3.2.3里面。

 Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58) Type "copyright", "credits" or "license" for more information. IPython 5.3.0 -- An enhanced Interactive Python. 

我怎么能解决这个错误和jupyter notebook 内embedded nltk图?

更新1

根据nltk树的来源http://www.nltk.org/_modules/nltk/draw/tree.html#draw_trees绘制它使用tkinter。

更新2

我已经在官方的nltk github仓库中提出了同样的问题https://github.com/nltk/nltk/issues/1765

更新3

我认为错误的原因可能是无头主机(docker)。 我已经安装了xvfb但似乎是足够的注意。

 RUN apt-get install -y xvfb 

我以为xvfb是默认启动的,但应该明确运行。 所以启动后我可以制作nltk树形图的截图。

 import os import nltk from IPython.display import Image chunkGram = r"""Chunk: {<RB.?>*<VB.?>*<NNP>+<NN>?}""" chunkParser = nltk.RegexpParser(chunkGram) tagged = [('Tonight', 'NN'), ('we', 'PRP'), ('are', 'VBP'), ('comforted', 'VBN'), ('by', 'IN'), ('the', 'DT'), ('hope', 'NN'), ('of', 'IN'), ('a', 'DT'), ('glad', 'JJ'), ('reunion', 'NN'), ('with', 'IN'), ('the', 'DT'), ('husband', 'NN'), ('who', 'WP'), ('was', 'VBD'), ('taken', 'VBN'), ('so', 'RB'), ('long', 'RB'), ('ago', 'RB'), (',', ','), ('and', 'CC'), ('we', 'PRP'), ('are', 'VBP'), ('grateful', 'JJ'), ('for', 'IN'), ('the', 'DT'), ('good', 'JJ'), ('life', 'NN'), ('of', 'IN'), ('Coretta', 'NNP'), ('Scott', 'NNP'), ('King', 'NNP'), ('.', '.')] chunked = chunkParser.parse(tagged) nltk.draw.tree.TreeView(chunked)._cframe.print_to_file('output.ps') os.system('convert output.ps output.png') Image(filename='output.png') 

[OUT]:

在这里输入图像说明

尝试在你的代码中join下面的代码片段

 import os import matplotlib as mpl if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') mpl.use('Agg') import matplotlib.pyplot as plt 

而不pipe。 你的问题是,Matplotlib对x-use后端的默认调用显然是一个问题。 这个答案绝不是唯一可能的解决scheme,但我认为这将解决您的问题。 请记住, 导入pyplot 之前切换后端非常重要。

或者,您可以尝试IPython.core.display.display(分块)

确保您的笔记本服务器是以-X标志设置启动的。

 def jupyter_draw_nltk_tree(tree): from IPython.display import Image, display from nltk.draw import TreeWidget from nltk.draw.util import CanvasFrame import subprocess cf = CanvasFrame() tc = TreeWidget(cf.canvas(), tree) tc['node_font'] = 'arial 13 bold' tc['leaf_font'] = 'arial 14' tc['node_color'] = '#005990' tc['leaf_color'] = '#3F8F57' tc['line_color'] = '#175252' cf.add_widget(tc, 10, 10) cf.print_to_file('tmp_tree_output.ps') cf.destroy() args = (['convert', 'tmp_tree_output.ps', 'tmp_tree_output.png']) subprocess.call(args) display(Image(filename='tmp_tree_output.png')) os.system('rm tmp_tree_output.ps tmp_tree_output.png') jupyter_draw_nltk_tree(chunked)