本文整理汇总了Python中nltk.draw.util.CanvasFrame类的典型用法代码示例。如果您正苦于以下问题:Python CanvasFrame类的具体用法?Python CanvasFrame怎么用?Python CanvasFrame使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CanvasFrame类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quicktree
def quicktree(sentence):
"""Parse a sentence and return a visual representation in IPython"""
import os
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
from stat_parser import Parser
try:
from IPython.display import display
from IPython.display import Image
except:
pass
try:
get_ipython().getoutput()
except TypeError:
have_ipython = True
except NameError:
import subprocess
have_ipython = False
parser = Parser()
parsed = parser.parse(sentence)
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),parsed)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file('tree.ps')
cf.destroy()
if have_ipython:
tregex_command = 'convert tree.ps tree.png'
result = get_ipython().getoutput(tregex_command)
else:
tregex_command = ["convert", "tree.ps", "tree.png"]
result = subprocess.check_output(tregex_command)
os.remove("tree.ps")
return Image(filename='tree.png')
os.remove("tree.png")
示例2: __init__
def __init__(self, trees, root=None):
if len(trees) == 0:
print "No trees to display."
return
newroot = False
if root is None:
root = Tkinter.Tk()
window = root
newroot = True
else:
window = Tkinter.Toplevel(root)
window.title("Parse Tree")
window.geometry("600x400")
self.cf = CanvasFrame(window)
self.cf.pack(side='top', expand=1, fill='both')
buttons = Tkinter.Frame(window)
buttons.pack(side='bottom', fill='x')
self.spin = Tkinter.Spinbox(buttons, from_=1, to=len(trees),
command=self.showtree, width=3)
if len(trees) > 1: self.spin.pack(side='left')
self.label = Tkinter.Label(buttons, text="of %d" % len(trees))
if len(trees) > 1: self.label.pack(side='left')
self.done = Tkinter.Button(buttons, text="Done", command=window.destroy)
self.done.pack(side='right')
self.printps = Tkinter.Button(buttons, text="Print to Postscript", command=self.cf.print_to_file)
self.printps.pack(side='right')
self.trees = trees
self.treeWidget = None
self.showtree()
if newroot: root.mainloop()
示例3: _init_canvas
def _init_canvas(self, parent):
self._cframe = CanvasFrame(
parent,
background='white',
width=525,
closeenough=10,
border=2,
relief='sunken',
)
self._cframe.pack(expand=1, fill='both', side='top', pady=2)
canvas = self._canvas = self._cframe.canvas()
self._stackwidgets = []
self._rtextwidgets = []
self._titlebar = canvas.create_rectangle(
0, 0, 0, 0, fill='#c0f0f0', outline='black'
)
self._exprline = canvas.create_line(0, 0, 0, 0, dash='.')
self._stacktop = canvas.create_line(0, 0, 0, 0, fill='#408080')
size = self._size.get() + 4
self._stacklabel = TextWidget(
canvas, 'Stack', color='#004040', font=self._boldfont
)
self._rtextlabel = TextWidget(
canvas, 'Remaining Text', color='#004040', font=self._boldfont
)
self._cframe.add_widget(self._stacklabel)
self._cframe.add_widget(self._rtextlabel)
示例4: drawrst
def drawrst(strtree, fname):
""" Draw RST tree into a file
"""
if not fname.endswith(".ps"):
fname += ".ps"
cf = CanvasFrame()
t = Tree.fromstring(strtree)
tc = TreeWidget(cf.canvas(), t)
cf.add_widget(tc,10,10) # (10,10) offsets
cf.print_to_file(fname)
cf.destroy()
示例5: tree_to_ps
def tree_to_ps(s, outfile):
global _canvas_frame
if _canvas_frame is None:
_canvas_frame = CanvasFrame()
# May throw ValueError:
widget = tree_to_widget(s, _canvas_frame.canvas())
_canvas_frame.canvas()['scrollregion'] = (0, 0, 1, 1)
_canvas_frame.add_widget(widget)
_canvas_frame.print_to_file(outfile)
bbox = widget.bbox()
_canvas_frame.destroy_widget(widget)
## Testing..
#for (key, val) in metrics.items():
# print key, '\n ', val
return bbox[2:]
示例6: to_ps
def to_ps(self, filename):
"""Export as a PostScript image.
This function is used by `_repr_png_`.
"""
_canvas_frame = CanvasFrame()
# WIP customization of visual appearance
# NB: conda-provided python and tk cannot access most fonts on the
# system, thus it currently falls back on the default font
widget = tree_to_treesegment(_canvas_frame.canvas(), self,
tree_yspace=35,
node_font=('Verdana', -18, 'bold'),
leaf_font=('Verdana', -18))
_canvas_frame.add_widget(widget)
x, y, w, h = widget.bbox()
# print_to_file uses scrollregion to set the width and height of the
# pdf
_canvas_frame.canvas()['scrollregion'] = (0, 0, w, h)
# print to file
_canvas_frame.print_to_file(filename)
_canvas_frame.destroy_widget(widget)
示例7: _init_canvas
def _init_canvas(self, parent):
self._cframe = CanvasFrame(parent, background='white',
#width=525, height=250,
closeenough=10,
border=2, relief='sunken')
self._cframe.pack(expand=1, fill='both', side='top', pady=2)
canvas = self._canvas = self._cframe.canvas()
# Initially, there's no tree or text
self._tree = None
self._textwidgets = []
self._textline = None
示例8: display_tree
def display_tree(tree):
if nltk_is_available:
count = 0
for t in tree:
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(), t)
cf.add_widget(tc, 10, 10)
count += 1
fileName = "tree" + repr(count) + ".ps"
cf.print_to_file(fileName)
cf.destroy()
else:
count = 0
for t in tree:
count += 1
fileName = "tree" + repr(count) + ".txt"
pprint.pprint(t, fileName)
示例9: _init_canvas
def _init_canvas(self, parent):
self._cframe = CanvasFrame(parent, background="white", width=525, closeenough=10, border=2, relief="sunken")
self._cframe.pack(expand=1, fill="both", side="top", pady=2)
canvas = self._canvas = self._cframe.canvas()
self._stackwidgets = []
self._rtextwidgets = []
self._titlebar = canvas.create_rectangle(0, 0, 0, 0, fill="#c0f0f0", outline="black")
self._exprline = canvas.create_line(0, 0, 0, 0, dash=".")
self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080")
size = self._size.get() + 4
self._stacklabel = TextWidget(canvas, "Stack", color="#004040", font=self._boldfont)
self._rtextlabel = TextWidget(canvas, "Remaining Text", color="#004040", font=self._boldfont)
self._cframe.add_widget(self._stacklabel)
self._cframe.add_widget(self._rtextlabel)
示例10: main
def main(args):
"""
Subcommand main.
You shouldn't need to call this yourself if you're using
`config_argparser`
"""
corpus = read_corpus(args)
odir = get_output_dir(args)
for key in corpus:
cframe = CanvasFrame()
widget = TreeWidget(cframe.canvas(), corpus[key])
cframe.add_widget(widget, 10, 10)
ofilename = fp.join(odir, key.doc) + '.ps'
cframe.print_to_file(ofilename)
cframe.destroy()
announce_output_dir(odir)
示例11: draw_tree
def draw_tree(tree_string):
raise NotImplementedError()
from nltk import Tree
from nltk.draw.util import CanvasFrame
from nltk.draw import TreeWidget
cf = CanvasFrame()
tree = Tree.fromstring(tree_string.replace('[','(').replace(']',')') )
cf.add_widget(TreeWidget(cf.canvas(), tree), 10, 10)
cf.print_to_file('tree.ps')
cf.destroy
示例12: execute
def execute(self, frase):
os.environ['STANFORD_PARSER'] = 'nltk/stanford-parser.jar'
os.environ['STANFORD_MODELS'] = 'nltk/stanford-parser-3.5.2-models.jar'
parser = stanford.StanfordParser(model_path="nltk/englishPCFG.ser.gz")
sentence = parser.raw_parse(frase)
print sentence
# GUI
for line in sentence:
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),line)
cf.add_widget(tc,40,40) # (10,10) offsets
cf.print_to_file('tree_stanford.ps')
#cf.destroy()
os.popen('convert tree_stanford.ps -resize 300% static/img/tree_stanford.png')
示例13: tagger
def tagger(self, frase):
#hacer el tag
text = nltk.word_tokenize(frase)
postag = nltk.pos_tag(text)
#convertirlo al formato lips
result = "("
for index in range(len(postag)):
result += "( " + postag[index][0] + " ( " + postag[index][1]+ " ) )"
result += ")"
#ejecutar bikel
#pasar resultado a archivo
#hoy = str(datetime.date.today())
f = open('prueba', 'w')
f.write(result)
f.close()
#consola = os.popen('tcsh ../dbparser/bin/parse 400 ../dbparser/settings/collins.properties ../wsj-02-21.obj.gz prueba')
args = shlex.split("tcsh ../dbparser/bin/parse 400 ../dbparser/settings/collins.properties ../wsj-02-21.obj.gz prueba")
print args
p = subprocess.Popen(args,stderr=subprocess.STDOUT)
p.wait()
f2 = open('prueba.parsed', 'r')
resultado = f2.read()
t = Tree.fromstring(resultado)
cf = CanvasFrame()
tc = TreeWidget(cf.canvas(),t)
cf.add_widget(tc,40,40) # (10,10) offsets
cf.print_to_file('tree_bikel.ps')
#cf.destroy()
os.popen('convert tree_bikel.ps -resize 300% static/img/tree_bikel.png')
return resultado
示例14: test
def test(parses):
def fill(cw):
cw['fill'] = '#%06d' % random.randint(0,999999)
cf = CanvasFrame(width=550, height=450, closeenough=2)
j = 10
for parse in parses:
t = Tree.fromstring(parse)
tc = TreeWidget(cf.canvas(), t, draggable=1,
node_font=('helvetica', -14, 'bold'),
leaf_font=('helvetica', -12, 'italic'),
roof_fill='white', roof_color='black',
leaf_color='green4', node_color='blue2')
cf.add_widget(tc,10,j)
tc.bind_click_trees(tc.toggle_collapsed)
j += 500
# Run mainloop
cf.mainloop()
示例15: RecursiveDescentApp
#.........这里部分代码省略.........
command=self.match).pack(side='left')
Button(buttonframe, text='Backtrack', underline=0,
background='#f0a0a0', foreground='black',
command=self.backtrack).pack(side='left')
# Replace autostep...
# self._autostep_button = Button(buttonframe, text='Autostep',
# underline=0, command=self.autostep)
# self._autostep_button.pack(side='left')
def _configure(self, event):
self._autostep = 0
(x1, y1, x2, y2) = self._cframe.scrollregion()
y2 = event.height - 6
self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
self._redraw()
def _init_feedback(self, parent):
self._feedbackframe = feedbackframe = Frame(parent)
feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
self._lastoper_label = Label(feedbackframe, text='Last Operation:',
font=self._font)
self._lastoper_label.pack(side='left')
lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
self._lastoper1 = Label(lastoperframe, foreground='#007070',
background='#f0f0f0', font=self._font)
self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
foreground='#004040', background='#f0f0f0',
font=self._font)
self._lastoper1.pack(side='left')
self._lastoper2.pack(side='left', fill='x', expand=1)
def _init_canvas(self, parent):
self._cframe = CanvasFrame(parent, background='white',
#width=525, height=250,
closeenough=10,
border=2, relief='sunken')
self._cframe.pack(expand=1, fill='both', side='top', pady=2)
canvas = self._canvas = self._cframe.canvas()
# Initially, there's no tree or text
self._tree = None
self._textwidgets = []
self._textline = None
def _init_menubar(self, parent):
menubar = Menu(parent)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label='Reset Parser', underline=0,
command=self.reset, accelerator='Del')
filemenu.add_command(label='Print to Postscript', underline=0,
command=self.postscript, accelerator='Ctrl-p')
filemenu.add_command(label='Exit', underline=1,
command=self.destroy, accelerator='Ctrl-x')
menubar.add_cascade(label='File', underline=0, menu=filemenu)
editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label='Edit Grammar', underline=5,
command=self.edit_grammar,
accelerator='Ctrl-g')
editmenu.add_command(label='Edit Text', underline=5,
command=self.edit_sentence,
accelerator='Ctrl-t')
menubar.add_cascade(label='Edit', underline=0, menu=editmenu)