Skip to content

Commit

Permalink
python/bllipparser/RerankingParser.py: More Tree visualization methods
Browse files Browse the repository at this point in the history
Added Tree.as_nltk_tree() and Tree.format_asciitree().

Tree.visualize_nltk() -> Tree.visualize(method='nltk') to leave the door
open for future visualization methods.
  • Loading branch information
dmcc committed Sep 4, 2015
1 parent e3cc257 commit b9f481b
Showing 1 changed file with 30 additions and 6 deletions.
36 changes: 30 additions & 6 deletions python/bllipparser/RerankingParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,25 @@ def __str__(self):
def pretty_string(self):
"""Represent the tree in Penn Treebank format with line wrapping."""
return self._tree.toStringPrettyPrint()
def format_asciitree(self):
"""Return a string representing this tree using asciitree
(requires the 'asciitree' package)."""
import asciitree
def child_iter(tree):
return tree.subtrees()
def text_str(tree):
return ' %s%s %s' % (tree.label, tree.label_suffix,
tree.token or '')
return asciitree.draw_tree(self, child_iter=child_iter,
text_str=text_str)
def as_nltk_tree(self):
"""Returns this tree as an NLTK Tree object."""
from .Utility import get_nltk_tree_reader_maybe
read_nltk_tree = get_nltk_tree_reader_maybe()
if not read_nltk_tree:
raise ImportError("Unable to import nltk tree reading.")
nltk_tree = read_nltk_tree(str(self))
return nltk_tree
def tokens(self):
"""Return a tuple of the word tokens in this tree."""
return tuple(self._tree.getWords())
Expand Down Expand Up @@ -168,12 +187,17 @@ def dependencies(self):
yield (head, subhead)
else:
tree_to_heads[tree.span()] = tree
def visualize_nltk(self):
from .Utility import get_nltk_tree_reader_maybe
read_nltk_tree = get_nltk_tree_reader_maybe()
if not read_nltk_tree:
raise ValueError("Unable to import nltk tree reading.")
nltk_tree = read_nltk_tree(str(self))
def visualize(self, method='nltk'):
"""Visualize this tree. The method argument determines the
method used for visualization. Currently 'nltk' is supported
(requires NLTK to be installed)."""
if method == 'nltk':
self._visualize_nltk()
else:
raise ValueError("Unknown visualization method: %r" % method)
def _visualize_nltk(self):
"""Visualize this tree using NLTK."""
nltk_tree = self.as_nltk_tree()
import nltk
nltk.draw.tree.draw_trees(nltk_tree)

Expand Down

0 comments on commit b9f481b

Please sign in to comment.