use tkinter for nltk draw inside of jupyter notebook
import osimport nltkfrom IPython.display import ImagechunkGram = 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]:
Try incorporating the following snippet in your code
import osimport matplotlib as mplif os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') mpl.use('Agg')import matplotlib.pyplot as plt
Regardless. Your problem is that Matplotlib's default call to an x-using backend is apparently causing a problem. This answer is by no means the only possible solution, but I think this will solve your problem.Remember that it is important to switch backend before importing pyplot.
Alternatively, you could try IPython.core.display.display(chunked)
Make sure that your notebook server is started with the -X flag set..
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)