Skip to content

Commit

Permalink
Merge pull request nltk#502 from stevenbird/master
Browse files Browse the repository at this point in the history
change tree node property to a method
  • Loading branch information
stevenbird committed Oct 17, 2013
2 parents 849558c + c13eafe commit 94f348a
Show file tree
Hide file tree
Showing 28 changed files with 181 additions and 151 deletions.
4 changes: 2 additions & 2 deletions nltk/app/chartparser_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def _click(self, widget):
width=2, outline='#088')

def _color(self, treewidget, color):
treewidget.node()['color'] = color
treewidget.label()['color'] = color
for child in treewidget.subtrees():
if isinstance(child, TreeSegmentWidget):
self._color(child, color)
Expand Down Expand Up @@ -1518,7 +1518,7 @@ def _draw_treetok(self, treetok, index, depth=0):
# Draw the node
nodey = depth * (ChartView._TREE_LEVEL_SIZE + self._text_height)
tag = c.create_text(nodex, nodey, anchor='n', justify='center',
text=str(treetok.node), fill='#042',
text=str(treetok.label()), fill='#042',
font=self._boldfont)
self._tree_tags.append(tag)

Expand Down
2 changes: 1 addition & 1 deletion nltk/app/chunkparser_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -993,7 +993,7 @@ def _chunks(self, tree):
wordnum = 0
for child in tree:
if isinstance(child, Tree):
if child.node == self._chunk_node:
if child.label() == self._chunk_node:
chunks.add( (wordnum, wordnum+len(child)) )
wordnum += len(child)
else:
Expand Down
24 changes: 12 additions & 12 deletions nltk/app/rdparser_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ def _init_menubar(self, parent):
def _get(self, widget, treeloc):
for i in treeloc: widget = widget.subtrees()[i]
if isinstance(widget, TreeSegmentWidget):
widget = widget.node()
widget = widget.label()
return widget

#########################################
Expand Down Expand Up @@ -465,7 +465,7 @@ def _position_text(self):
widget = self._textwidgets[i]
leaf = leaves[i]
dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10)
dy = max(dy, leaf.parent().label().bbox()[3] - leaf.bbox()[3] + 10)
leaf.move(0, dy)

def _tree_leaves(self, tree=None):
Expand Down Expand Up @@ -687,23 +687,23 @@ def _animate_expand(self, treeloc):
tree_width=2, tree_color='white',
node_color='white',
leaf_font=self._font)
widget.node()['color'] = '#20a050'
widget.label()['color'] = '#20a050'

(oldx, oldy) = oldtree.node().bbox()[:2]
(newx, newy) = widget.node().bbox()[:2]
(oldx, oldy) = oldtree.label().bbox()[:2]
(newx, newy) = widget.label().bbox()[:2]
widget.move(oldx-newx, oldy-newy)

if top:
self._cframe.add_widget(widget, 0, 5)
widget.move(30-widget.node().bbox()[0], 0)
widget.move(30-widget.label().bbox()[0], 0)
self._tree = widget
else:
oldtree.parent().replace_child(oldtree, widget)

# Move the children over so they don't overlap.
# Line the children up in a strange way.
if widget.subtrees():
dx = (oldx + widget.node().width()/2 -
dx = (oldx + widget.label().width()/2 -
widget.subtrees()[0].bbox()[0]/2 -
widget.subtrees()[0].bbox()[2]/2)
for subtree in widget.subtrees(): subtree.move(dx, 0)
Expand Down Expand Up @@ -756,7 +756,7 @@ def _animate_expand_frame(self, widget, colors):
widget['color'] = colors[0]
for subtree in widget.subtrees():
if isinstance(subtree, TreeSegmentWidget):
subtree.node()['color'] = colors[0]
subtree.label()['color'] = colors[0]
else:
subtree['color'] = colors[0]
self._top.after(50, self._animate_expand_frame,
Expand All @@ -765,11 +765,11 @@ def _animate_expand_frame(self, widget, colors):
widget['color'] = 'black'
for subtree in widget.subtrees():
if isinstance(subtree, TreeSegmentWidget):
subtree.node()['color'] = 'black'
subtree.label()['color'] = 'black'
else:
subtree['color'] = 'black'
self._redraw_quick()
widget.node()['color'] = 'black'
widget.label()['color'] = 'black'
self._animating_lock = 0
if self._autostep: self._step()

Expand All @@ -783,7 +783,7 @@ def _animate_backtrack(self, treeloc):
widgets = [self._get(self._tree, treeloc).parent()]
for subtree in widgets[0].subtrees():
if isinstance(subtree, TreeSegmentWidget):
widgets.append(subtree.node())
widgets.append(subtree.label())
else:
widgets.append(subtree)

Expand All @@ -805,7 +805,7 @@ def _animate_backtrack_frame(self, widgets, colors):

def _animate_match_backtrack(self, treeloc):
widget = self._get(self._tree, treeloc)
node = widget.parent().node()
node = widget.parent().label()
dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
max(1, self._animation_frames.get()))
self._animate_match_backtrack_frame(self._animation_frames.get(),
Expand Down
10 changes: 5 additions & 5 deletions nltk/app/srparser_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ def _redraw(self):
'leaf_color': '#006060', 'leaf_font':self._font}
widget = tree_to_treesegment(self._canvas, tok,
**attribs)
widget.node()['color'] = '#000000'
widget.label()['color'] = '#000000'
else:
widget = TextWidget(self._canvas, tok,
color='#000000', font=self._font)
Expand Down Expand Up @@ -665,7 +665,7 @@ def _animate_reduce(self):

# How far are we moving?
if isinstance(widgets[0], TreeSegmentWidget):
ydist = 15 + widgets[0].node().height()
ydist = 15 + widgets[0].label().height()
else:
ydist = 15 + widgets[0].height()

Expand All @@ -686,7 +686,7 @@ def _animate_reduce_frame(self, frame, widgets, dy):
self._cframe.remove_widget(widget)
tok = self._parser.stack()[-1]
if not isinstance(tok, Tree): raise ValueError()
label = TextWidget(self._canvas, str(tok.node), color='#006060',
label = TextWidget(self._canvas, str(tok.label()), color='#006060',
font=self._boldfont)
widget = TreeSegmentWidget(self._canvas, label, widgets,
width=2)
Expand Down Expand Up @@ -748,7 +748,7 @@ def _highlight_hover(self, event):
rhslen = len(self._productions[index].rhs())
for stackwidget in self._stackwidgets[-rhslen:]:
if isinstance(stackwidget, TreeSegmentWidget):
stackwidget.node()['color'] = '#00a000'
stackwidget.label()['color'] = '#00a000'
else:
stackwidget['color'] = '#00a000'

Expand All @@ -761,7 +761,7 @@ def _clear_hover(self, *event):
self._hover = -1
for stackwidget in self._stackwidgets:
if isinstance(stackwidget, TreeSegmentWidget):
stackwidget.node()['color'] = 'black'
stackwidget.label()['color'] = 'black'
else:
stackwidget['color'] = 'black'

Expand Down
8 changes: 4 additions & 4 deletions nltk/ccg/chart.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,15 +297,15 @@ def printCCGTree(lwidth,tree):

# Find the width of the current derivation step
for child in tree:
rwidth = max(rwidth,printCCGTree(rwidth,child))
rwidth = max(rwidth, printCCGTree(rwidth,child))

# Is a leaf node.
# Don't print anything, but account for the space occupied.
if not isinstance(tree.node, tuple):
return max(rwidth,2 + lwidth + len("%s" % tree.node),
if not isinstance(tree.label(), tuple):
return max(rwidth,2 + lwidth + len("%s" % tree.label()),
2 + lwidth + len(tree[0]))

(res,op) = tree.node
(res,op) = tree.label()
# Pad to the left with spaces, followed by a sequence of '-'
# and the derivation rule.
print(lwidth*' ' + (rwidth-lwidth)*'-' + "%s" % op)
Expand Down
8 changes: 4 additions & 4 deletions nltk/chunk/named_entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def _tagged_to_parse(self, tagged_tokens):
sent.append(Tree(tag[2:], [tok]))
elif tag.startswith('I-'):
if (sent and isinstance(sent[-1], Tree) and
sent[-1].node == tag[2:]):
sent[-1].label() == tag[2:]):
sent[-1].append(tok)
else:
sent.append(Tree(tag[2:], [tok]))
Expand All @@ -159,9 +159,9 @@ def _parse_to_tagged(sent):
if len(child) == 0:
print("Warning -- empty chunk in sentence")
continue
toks.append((child[0], 'B-%s' % child.node))
toks.append((child[0], 'B-%s' % child.label()))
for tok in child[1:]:
toks.append((tok, 'I-%s' % child.node))
toks.append((tok, 'I-%s' % child.label()))
else:
toks.append((child, 'O'))
return toks
Expand Down Expand Up @@ -191,7 +191,7 @@ def postag_tree(tree):
newtree = Tree('S', [])
for child in tree:
if isinstance(child, Tree):
newtree.append(Tree(child.node, []))
newtree.append(Tree(child.label(), []))
for subchild in child:
newtree[-1].append( (subchild, next(tag_iter)) )
else:
Expand Down
6 changes: 3 additions & 3 deletions nltk/chunk/regexp.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def __init__(self, chunk_struct, debug_level=1):
probably use level 3 if you use any non-standard
subclasses of ``RegexpChunkRule``.
"""
self._top_node = chunk_struct.node
self._top_node = chunk_struct.label()
self._pieces = chunk_struct[:]
tags = [self._tag(tok) for tok in self._pieces]
self._str = '<' + '><'.join(tags) + '>'
Expand All @@ -100,7 +100,7 @@ def _tag(self, tok):
if isinstance(tok, tuple):
return tok[1]
elif isinstance(tok, Tree):
return tok.node
return tok.label()
else:
raise ValueError('chunk structures must contain tagged '
'tokens or trees')
Expand Down Expand Up @@ -1007,7 +1007,7 @@ def parse(self, chunk_struct, trace=None):
return Tree(self._top_node, [])

try:
chunk_struct.node
chunk_struct.label()
except AttributeError:
chunk_struct = Tree(self._top_node, chunk_struct)

Expand Down
8 changes: 4 additions & 4 deletions nltk/chunk/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ def _chunksets(t, count, chunk_node):
chunks = []
for child in t:
if isinstance(child, Tree):
if re.match(chunk_node, child.node):
if re.match(chunk_node, child.label()):
chunks.append(((count, pos), child.freeze()))
pos += len(child.leaves())
else:
Expand Down Expand Up @@ -389,7 +389,7 @@ def conllstr2tree(s, chunk_types=('NP', 'PP', 'VP'), top_node="S"):

# For "Begin"/"Outside", finish any completed chunks -
# also do so for "Inside" which don't match the previous token.
mismatch_I = state == 'I' and chunk_type != stack[-1].node
mismatch_I = state == 'I' and chunk_type != stack[-1].label()
if state in 'BO' or mismatch_I:
if len(stack) == 2: stack.pop()

Expand Down Expand Up @@ -417,7 +417,7 @@ def tree2conlltags(t):
tags = []
for child in t:
try:
category = child.node
category = child.label()
prefix = "B-"
for contents in child:
if isinstance(contents, Tree):
Expand Down Expand Up @@ -445,7 +445,7 @@ def conlltags2tree(sentence, chunk_types=('NP','PP','VP'),
tree.append(Tree(chunktag[2:], [(word,postag)]))
elif chunktag.startswith('I-'):
if (len(tree)==0 or not isinstance(tree[-1], Tree) or
tree[-1].node != chunktag[2:]):
tree[-1].label() != chunktag[2:]):
if strict:
raise ValueError("Bad conll tag sequence")
else:
Expand Down
8 changes: 4 additions & 4 deletions nltk/corpus/reader/conll.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def _get_chunked_words(self, grid, chunk_types, tagset=None):
if chunk_types is not None and chunk_type not in chunk_types:
state = 'O'
# Treat a mismatching I like a B.
if state == 'I' and chunk_type != stack[-1].node:
if state == 'I' and chunk_type != stack[-1].label():
state = 'B'
# For B or I: close any open chunks
if state in 'BO' and len(stack) == 2:
Expand Down Expand Up @@ -290,7 +290,7 @@ def _get_parsed_sent(self, grid, pos_in_tree, tagset=None):
for i, child in enumerate(subtree):
if (isinstance(child, Tree) and len(child)==1 and
isinstance(child[0], compat.string_types)):
subtree[i] = (child[0], child.node)
subtree[i] = (child[0], child.label())

return tree

Expand Down Expand Up @@ -493,15 +493,15 @@ def pprint(self, include_tree=False):
def _tree2conll(self, tree, wordnum, words, pos, synt):
assert isinstance(tree, Tree)
if len(tree) == 1 and isinstance(tree[0], compat.string_types):
pos[wordnum] = tree.node
pos[wordnum] = tree.label()
assert words[wordnum] == tree[0]
return wordnum+1
elif len(tree) == 1 and isinstance(tree[0], tuple):
assert len(tree[0]) == 2
pos[wordnum], pos[wordnum] = tree[0]
return wordnum+1
else:
synt[wordnum] = '(%s%s' % (tree.node, synt[wordnum])
synt[wordnum] = '(%s%s' % (tree.label(), synt[wordnum])
for child in tree:
wordnum = self._tree2conll(child, wordnum, words,
pos, synt)
Expand Down
2 changes: 1 addition & 1 deletion nltk/draw/cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,7 +615,7 @@ def _markproduction(self, prod, tree=None):
widget = tree.subtrees()[i+j]
if (isinstance(node, Nonterminal) and
isinstance(widget, TreeSegmentWidget) and
node.symbol == widget.node().text()):
node.symbol == widget.label().text()):
pass # matching nonterminal
elif (isinstance(node, compat.string_types) and
isinstance(widget, TextWidget) and
Expand Down
16 changes: 8 additions & 8 deletions nltk/draw/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def _tags(self):

def _subtree_top(self, child):
if isinstance(child, TreeSegmentWidget):
bbox = child.node().bbox()
bbox = child.label().bbox()
else:
bbox = child.bbox()
if self._horizontal:
Expand Down Expand Up @@ -394,7 +394,7 @@ def _tree_to_treeseg(canvas, t, make_node, make_leaf,
tree_attribs, node_attribs,
leaf_attribs, loc_attribs):
if isinstance(t, Tree):
node = make_node(canvas, t.node, **node_attribs)
node = make_node(canvas, t.label(), **node_attribs)
subtrees = [_tree_to_treeseg(canvas, child, make_node, make_leaf,
tree_attribs, node_attribs,
leaf_attribs, loc_attribs)
Expand Down Expand Up @@ -592,7 +592,7 @@ def _make_collapsed_trees(self, canvas, t, key):
make_node = self._make_node
make_leaf = self._make_leaf

node = make_node(canvas, t.node, **self._nodeattribs)
node = make_node(canvas, t.label(), **self._nodeattribs)
self._nodes.append(node)
leaves = [make_leaf(canvas, l, **self._leafattribs)
for l in t.leaves()]
Expand All @@ -617,7 +617,7 @@ def _make_expanded_tree(self, canvas, t, key):
make_leaf = self._make_leaf

if isinstance(t, Tree):
node = make_node(canvas, t.node, **self._nodeattribs)
node = make_node(canvas, t.label(), **self._nodeattribs)
self._nodes.append(node)
children = t
subtrees = [self._make_expanded_tree(canvas, children[i], key+(i,))
Expand Down Expand Up @@ -735,8 +735,8 @@ def toggle_collapsed(self, treeseg):
# Move the new tree to where the old tree was. Show it first,
# so we can find its bounding box.
new_treeseg.show()
(newx, newy) = new_treeseg.node().bbox()[:2]
(oldx, oldy) = old_treeseg.node().bbox()[:2]
(newx, newy) = new_treeseg.label().bbox()[:2]
(oldx, oldy) = old_treeseg.label().bbox()[:2]
new_treeseg.move(oldx-newx, oldy-newy)

# Hide the old tree
Expand Down Expand Up @@ -901,8 +901,8 @@ def ovalit(canvas, text):
def color(node):
node['color'] = '#%04d00' % random.randint(0,9999)
def color2(treeseg):
treeseg.node()['fill'] = '#%06d' % random.randint(0,9999)
treeseg.node().child()['color'] = 'white'
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)
Expand Down
4 changes: 2 additions & 2 deletions nltk/parse/pchart.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,11 +253,11 @@ def _setprob(self, tree, prod_probs):
if tree.prob() is not None: return

# Get the prob of the CFG production.
lhs = Nonterminal(tree.node)
lhs = Nonterminal(tree.label())
rhs = []
for child in tree:
if isinstance(child, Tree):
rhs.append(Nonterminal(child.node))
rhs.append(Nonterminal(child.label()))
else:
rhs.append(child)
prob = prod_probs[lhs, tuple(rhs)]
Expand Down
Loading

0 comments on commit 94f348a

Please sign in to comment.