本文整理汇总了Python中nltk.draw.util.CanvasFrame.canvas方法的典型用法代码示例。如果您正苦于以下问题:Python CanvasFrame.canvas方法的具体用法?Python CanvasFrame.canvas怎么用?Python CanvasFrame.canvas使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nltk.draw.util.CanvasFrame
的用法示例。
在下文中一共展示了CanvasFrame.canvas方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: quicktree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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: tree_to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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:]
示例3: drawrst
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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()
示例4: draw_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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
示例5: to_ps
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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)
示例6: display_tree
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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)
示例7: main
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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)
示例8: execute
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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')
示例9: tagger
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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
示例10: __init__
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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)
示例11: test
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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 canvas [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 canvas [as 别名]
class RecursiveDescentApp(object):
"""
A graphical tool for exploring the recursive descent parser. The tool
displays the parser's tree and the remaining text, and allows the
user to control the parser's operation. In particular, the user
can expand subtrees on the frontier, match tokens on the frontier
against the text, and backtrack. A "step" button simply steps
through the parsing process, performing the operations that
``RecursiveDescentParser`` would use.
"""
def __init__(self, grammar, sent, trace=0):
self._sent = sent
self._parser = SteppingRecursiveDescentParser(grammar, trace)
# Set up the main window.
self._top = Tk()
self._top.title('Recursive Descent Parser Application')
# Set up key bindings.
self._init_bindings()
# Initialize the fonts.
self._init_fonts(self._top)
# Animations. animating_lock is a lock to prevent the demo
# from performing new operations while it's animating.
self._animation_frames = IntVar(self._top)
self._animation_frames.set(5)
self._animating_lock = 0
self._autostep = 0
# The user can hide the grammar.
self._show_grammar = IntVar(self._top)
self._show_grammar.set(1)
# Create the basic frames.
self._init_menubar(self._top)
self._init_buttons(self._top)
self._init_feedback(self._top)
self._init_grammar(self._top)
self._init_canvas(self._top)
# Initialize the parser.
self._parser.initialize(self._sent)
# Resize callback
self._canvas.bind('<Configure>', self._configure)
#########################################
## Initialization Helpers
#########################################
def _init_fonts(self, root):
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
self._sysfont = tkFont.Font(font=Button()["font"])
root.option_add("*Font", self._sysfont)
# TWhat's our font size (default=same as sysfont)
self._size = IntVar(root)
self._size.set(self._sysfont.cget('size'))
self._boldfont = tkFont.Font(family='helvetica', weight='bold',
size=self._size.get())
self._font = tkFont.Font(family='helvetica',
size=self._size.get())
if self._size.get() < 0: big = self._size.get()-2
else: big = self._size.get()+2
self._bigfont = tkFont.Font(family='helvetica', weight='bold',
size=big)
def _init_grammar(self, parent):
# Grammar view.
self._prodframe = listframe = Frame(parent)
self._prodframe.pack(fill='both', side='left', padx=2)
self._prodlist_label = Label(self._prodframe, font=self._boldfont,
text='Available Expansions')
self._prodlist_label.pack()
self._prodlist = Listbox(self._prodframe, selectmode='single',
relief='groove', background='white',
foreground='#909090', font=self._font,
selectforeground='#004040',
selectbackground='#c0f0c0')
self._prodlist.pack(side='right', fill='both', expand=1)
self._productions = list(self._parser.grammar().productions())
for production in self._productions:
self._prodlist.insert('end', (' %s' % production))
self._prodlist.config(height=min(len(self._productions), 25))
# Add a scrollbar if there are more than 25 productions.
if len(self._productions) > 25:
listscroll = Scrollbar(self._prodframe,
orient='vertical')
self._prodlist.config(yscrollcommand = listscroll.set)
listscroll.config(command=self._prodlist.yview)
listscroll.pack(side='left', fill='y')
# If they select a production, apply it.
self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)
#.........这里部分代码省略.........
示例14: demo
# 需要导入模块: from nltk.draw.util import CanvasFrame [as 别名]
# 或者: from nltk.draw.util.CanvasFrame import canvas [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 canvas [as 别名]
class ShiftReduceApp(object):
"""
A graphical tool for exploring the shift-reduce parser. The tool
displays the parser's stack and the remaining text, and allows the
user to control the parser's operation. In particular, the user
can shift tokens onto the stack, and can perform reductions on the
top elements of the stack. A "step" button simply steps through
the parsing process, performing the operations that
``nltk.parse.ShiftReduceParser`` would use.
"""
def __init__(self, grammar, sent, trace=0):
self._sent = sent
self._parser = SteppingShiftReduceParser(grammar, trace)
# Set up the main window.
self._top = Tk()
self._top.title('Shift Reduce Parser Application')
# Animations. animating_lock is a lock to prevent the demo
# from performing new operations while it's animating.
self._animating_lock = 0
self._animate = IntVar(self._top)
self._animate.set(10) # = medium
# The user can hide the grammar.
self._show_grammar = IntVar(self._top)
self._show_grammar.set(1)
# Initialize fonts.
self._init_fonts(self._top)
# Set up key bindings.
self._init_bindings()
# Create the basic frames.
self._init_menubar(self._top)
self._init_buttons(self._top)
self._init_feedback(self._top)
self._init_grammar(self._top)
self._init_canvas(self._top)
# A popup menu for reducing.
self._reduce_menu = Menu(self._canvas, tearoff=0)
# Reset the demo, and set the feedback frame to empty.
self.reset()
self._lastoper1['text'] = ''
#########################################
## Initialization Helpers
#########################################
def _init_fonts(self, root):
# See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
self._sysfont = tkinter.font.Font(font=Button()["font"])
root.option_add("*Font", self._sysfont)
# TWhat's our font size (default=same as sysfont)
self._size = IntVar(root)
self._size.set(self._sysfont.cget('size'))
self._boldfont = tkinter.font.Font(family='helvetica', weight='bold',
size=self._size.get())
self._font = tkinter.font.Font(family='helvetica',
size=self._size.get())
def _init_grammar(self, parent):
# Grammar view.
self._prodframe = listframe = Frame(parent)
self._prodframe.pack(fill='both', side='left', padx=2)
self._prodlist_label = Label(self._prodframe,
font=self._boldfont,
text='Available Reductions')
self._prodlist_label.pack()
self._prodlist = Listbox(self._prodframe, selectmode='single',
relief='groove', background='white',
foreground='#909090',
font=self._font,
selectforeground='#004040',
selectbackground='#c0f0c0')
self._prodlist.pack(side='right', fill='both', expand=1)
self._productions = list(self._parser.grammar().productions())
for production in self._productions:
self._prodlist.insert('end', (' %s' % production))
self._prodlist.config(height=min(len(self._productions), 25))
# Add a scrollbar if there are more than 25 productions.
if 1:#len(self._productions) > 25:
listscroll = Scrollbar(self._prodframe,
orient='vertical')
self._prodlist.config(yscrollcommand = listscroll.set)
listscroll.config(command=self._prodlist.yview)
listscroll.pack(side='left', fill='y')
# If they select a production, apply it.
self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)
# When they hover over a production, highlight it.
#.........这里部分代码省略.........