本文整理汇总了Python中nltk.draw.util.CanvasFrame.add_widget方法的典型用法代码示例。如果您正苦于以下问题:Python CanvasFrame.add_widget方法的具体用法?Python CanvasFrame.add_widget怎么用?Python CanvasFrame.add_widget使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nltk.draw.util.CanvasFrame
的用法示例。
在下文中一共展示了CanvasFrame.add_widget方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quicktree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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: drawrst
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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()
示例3: draw_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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
示例4: execute
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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')
示例5: display_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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)
示例6: main
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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)
示例7: tagger
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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
示例8: __init__
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
class TreeView:
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()
def showtree(self):
try: n = int(self.spin.get())
except ValueError: n=1
if self.treeWidget is not None: self.cf.destroy_widget(self.treeWidget)
self.treeWidget = TreeWidget(self.cf.canvas(),
self.trees[n-1], draggable=1, shapeable=1)
self.cf.add_widget(self.treeWidget, 0, 0)
示例9: tree_to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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:]
示例10: to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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)
示例11: test
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
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()
示例12: CFGDemo
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
class CFGDemo(object):
def __init__(self, grammar, text):
self._grammar = grammar
self._text = text
# Set up the main window.
self._top = Tk()
self._top.title('Context Free Grammar Demo')
# Base font size
self._size = IntVar(self._top)
self._size.set(12) # = medium
# Set up the key bindings
self._init_bindings(self._top)
# Create the basic frames
frame1 = Frame(self._top)
frame1.pack(side='left', fill='y', expand=0)
self._init_menubar(self._top)
self._init_buttons(self._top)
self._init_grammar(frame1)
self._init_treelet(frame1)
self._init_workspace(self._top)
#//////////////////////////////////////////////////
# Initialization
#//////////////////////////////////////////////////
def _init_bindings(self, top):
top.bind('<Control-q>', self.destroy)
def _init_menubar(self, parent): pass
def _init_buttons(self, parent): pass
def _init_grammar(self, parent):
self._prodlist = ProductionList(parent, self._grammar, width=20)
self._prodlist.pack(side='top', fill='both', expand=1)
self._prodlist.focus()
self._prodlist.add_callback('select', self._selectprod_cb)
self._prodlist.add_callback('move', self._selectprod_cb)
def _init_treelet(self, parent):
self._treelet_canvas = Canvas(parent, background='white')
self._treelet_canvas.pack(side='bottom', fill='x')
self._treelet = None
def _init_workspace(self, parent):
self._workspace = CanvasFrame(parent, background='white')
self._workspace.pack(side='right', fill='both', expand=1)
self._tree = None
self.reset_workspace()
#//////////////////////////////////////////////////
# Workspace
#//////////////////////////////////////////////////
def reset_workspace(self):
c = self._workspace.canvas()
fontsize = int(self._size.get())
node_font = ('helvetica', -(fontsize+4), 'bold')
leaf_font = ('helvetica', -(fontsize+2))
# Remove the old tree
if self._tree is not None:
self._workspace.remove_widget(self._tree)
# The root of the tree.
start = self._grammar.start().symbol()
rootnode = TextWidget(c, start, font=node_font, draggable=1)
# The leaves of the tree.
leaves = []
for word in self._text:
leaves.append(TextWidget(c, word, font=leaf_font, draggable=1))
# Put it all together into one tree
self._tree = TreeSegmentWidget(c, rootnode, leaves,
color='white')
# Add it to the workspace.
self._workspace.add_widget(self._tree)
# Move the leaves to the bottom of the workspace.
for leaf in leaves: leaf.move(0,100)
#self._nodes = {start:1}
#self._leaves = dict([(l,1) for l in leaves])
def workspace_markprod(self, production):
pass
def _markproduction(self, prod, tree=None):
if tree is None: tree = self._tree
for i in range(len(tree.subtrees())-len(prod.rhs())):
if tree['color', i] == 'white':
self._markproduction
for j, node in enumerate(prod.rhs()):
#.........这里部分代码省略.........
示例13: RecursiveDescentApp
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
#.........这里部分代码省略.........
#########################################
## Helper
#########################################
def _get(self, widget, treeloc):
for i in treeloc: widget = widget.subtrees()[i]
if isinstance(widget, TreeSegmentWidget):
widget = widget.node()
return widget
#########################################
## Main draw procedure
#########################################
def _redraw(self):
canvas = self._canvas
# Delete the old tree, widgets, etc.
if self._tree is not None:
self._cframe.destroy_widget(self._tree)
for twidget in self._textwidgets:
self._cframe.destroy_widget(twidget)
if self._textline is not None:
self._canvas.delete(self._textline)
# Draw the tree.
helv = ('helvetica', -self._size.get())
bold = ('helvetica', -self._size.get(), 'bold')
attribs = {'tree_color': '#000000', 'tree_width': 2,
'node_font': bold, 'leaf_font': helv,}
tree = self._parser.tree()
self._tree = tree_to_treesegment(canvas, tree, **attribs)
self._cframe.add_widget(self._tree, 30, 5)
# Draw the text.
helv = ('helvetica', -self._size.get())
bottom = y = self._cframe.scrollregion()[3]
self._textwidgets = [TextWidget(canvas, word, font=self._font)
for word in self._sent]
for twidget in self._textwidgets:
self._cframe.add_widget(twidget, 0, 0)
twidget.move(0, bottom-twidget.bbox()[3]-5)
y = min(y, twidget.bbox()[1])
# Draw a line over the text, to separate it from the tree.
self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')
# Highlight appropriate nodes.
self._highlight_nodes()
self._highlight_prodlist()
# Make sure the text lines up.
self._position_text()
def _redraw_quick(self):
# This should be more-or-less sufficient after an animation.
self._highlight_nodes()
self._highlight_prodlist()
self._position_text()
def _highlight_nodes(self):
# Highlight the list of nodes to be checked.
bold = ('helvetica', -self._size.get(), 'bold')
for treeloc in self._parser.frontier()[:1]:
示例14: demo
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
def demo():
import random
def fill(cw):
cw['fill'] = '#%06d' % random.randint(0, 999999)
cf = CanvasFrame(width=550, height=450, closeenough=2)
t = Tree.fromstring(
'''
(S (NP the very big cat)
(VP (Adv sorta) (V saw) (NP (Det the) (N dog))))'''
)
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, 10)
def boxit(canvas, text):
big = ('helvetica', -16, 'bold')
return BoxWidget(canvas, TextWidget(canvas, text, font=big), fill='green')
def ovalit(canvas, text):
return OvalWidget(canvas, TextWidget(canvas, text), fill='cyan')
treetok = Tree.fromstring('(S (NP this tree) (VP (V is) (AdjP shapeable)))')
tc2 = TreeWidget(cf.canvas(), treetok, boxit, ovalit, shapeable=1)
def color(node):
node['color'] = '#%04d00' % random.randint(0, 9999)
def color2(treeseg):
treeseg.label()['fill'] = '#%06d' % random.randint(0, 9999)
treeseg.label().child()['color'] = 'white'
tc.bind_click_trees(tc.toggle_collapsed)
tc2.bind_click_trees(tc2.toggle_collapsed)
tc.bind_click_nodes(color, 3)
tc2.expanded_tree(1).bind_click(color2, 3)
tc2.expanded_tree().bind_click(color2, 3)
paren = ParenWidget(cf.canvas(), tc2)
cf.add_widget(paren, tc.bbox()[2] + 10, 10)
tree3 = Tree.fromstring(
'''
(S (NP this tree) (AUX was)
(VP (V built) (PP (P with) (NP (N tree_to_treesegment)))))'''
)
tc3 = tree_to_treesegment(
cf.canvas(), tree3, tree_color='green4', tree_xspace=2, tree_width=2
)
tc3['draggable'] = 1
cf.add_widget(tc3, 10, tc.bbox()[3] + 10)
def orientswitch(treewidget):
if treewidget['orientation'] == 'horizontal':
treewidget.expanded_tree(1, 1).subtrees()[0].set_text('vertical')
treewidget.collapsed_tree(1, 1).subtrees()[0].set_text('vertical')
treewidget.collapsed_tree(1).subtrees()[1].set_text('vertical')
treewidget.collapsed_tree().subtrees()[3].set_text('vertical')
treewidget['orientation'] = 'vertical'
else:
treewidget.expanded_tree(1, 1).subtrees()[0].set_text('horizontal')
treewidget.collapsed_tree(1, 1).subtrees()[0].set_text('horizontal')
treewidget.collapsed_tree(1).subtrees()[1].set_text('horizontal')
treewidget.collapsed_tree().subtrees()[3].set_text('horizontal')
treewidget['orientation'] = 'horizontal'
text = """
Try clicking, right clicking, and dragging
different elements of each of the trees.
The top-left tree is a TreeWidget built from
a Tree. The top-right is a TreeWidget built
from a Tree, using non-default widget
constructors for the nodes & leaves (BoxWidget
and OvalWidget). The bottom-left tree is
built from tree_to_treesegment."""
twidget = TextWidget(cf.canvas(), text.strip())
textbox = BoxWidget(cf.canvas(), twidget, fill='white', draggable=1)
cf.add_widget(textbox, tc3.bbox()[2] + 10, tc2.bbox()[3] + 10)
tree4 = Tree.fromstring('(S (NP this tree) (VP (V is) (Adj horizontal)))')
tc4 = TreeWidget(
cf.canvas(),
tree4,
draggable=1,
line_color='brown2',
roof_color='brown2',
node_font=('helvetica', -12, 'bold'),
node_color='brown4',
#.........这里部分代码省略.........
示例15: ShiftReduceApp
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import add_widget [as 别名]
#.........这里部分代码省略.........
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, 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)
#########################################
## Main draw procedure
#########################################
def _redraw(self):
scrollregion = self._canvas['scrollregion'].split()
(cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]
# Delete the old stack & rtext widgets.
for stackwidget in self._stackwidgets:
self._cframe.destroy_widget(stackwidget)
self._stackwidgets = []
for rtextwidget in self._rtextwidgets:
self._cframe.destroy_widget(rtextwidget)
self._rtextwidgets = []
# Position the titlebar & exprline
(x1, y1, x2, y2) = self._stacklabel.bbox()
y = y2-y1+10
self._canvas.coords(self._titlebar, -5000, 0, 5000, y-4)
self._canvas.coords(self._exprline, 0, y*2-10, 5000, y*2-10)
# Position the titlebar labels..
(x1, y1, x2, y2) = self._stacklabel.bbox()
self._stacklabel.move(5-x1, 3-y1)
(x1, y1, x2, y2) = self._rtextlabel.bbox()
self._rtextlabel.move(cx2-x2-5, 3-y1)
# Draw the stack.
stackx = 5