我试图在nltk
内绘制jupyter-notebook
的图表(内嵌)。但得到了错误:
TclError: no display name and no $DISPLAY environment variable
我尝试将$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最后一个单元格。
环境:官方anaconda3码头工具 - 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.
我如何在nltk
内解决此错误和内嵌 jupyter notebook
图表?
http://www.nltk.org/_modules/nltk/draw/tree.html#draw_trees根据nltk树的来源绘制它使用tkinter
。
我在官方nltk github存储库https://github.com/nltk/nltk/issues/1765
中提出了同样的问题我认为错误的原因可能是无头主机(docker)。我已经安装了xvfb
,但似乎已经足够注意了。
RUN apt-get install -y xvfb
我认为xvfb
默认启动,但应该明确运行。所以在我发布之后,我可以制作nltk树形图的截图。
答案 0 :(得分:1)
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]:
答案 1 :(得分:0)
尝试在代码中加入以下代码段
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
不管。你的问题是Matplotlib默认调用x-using后端显然会导致问题。这个答案绝不是唯一可行的解决方案,但我认为这将解决您的问题。 请记住,在导入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)