Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# -*- coding: utf-8 -*- # Natural Language Toolkit: A Chart Parser # # Copyright (C) 2001-2012 NLTK Project # Author: Edward Loper <edloper@gradient.cis.upenn.edu> # Steven Bird <sb@csse.unimelb.edu.au> # Jean Mark Gawron <gawron@mail.sdsu.edu> # Peter Ljunglöf <peter.ljunglof@heatherleaf.se> # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT
Data classes and parser implementations for "chart parsers", which use dynamic programming to efficiently parse a text. A chart parser derives parse trees for a text by iteratively adding "edges" to a "chart." Each edge represents a hypothesis about the tree structure for a subsequence of the text. The chart is a "blackboard" for composing and combining these hypotheses.
When a chart parser begins parsing a text, it creates a new (empty) chart, spanning the text. It then incrementally adds new edges to the chart. A set of "chart rules" specifies the conditions under which new edges should be added to the chart. Once the chart reaches a stage where none of the chart rules adds any new edges, parsing is complete.
Charts are encoded with the ``Chart`` class, and edges are encoded with the ``TreeEdge`` and ``LeafEdge`` classes. The chart parser module defines three chart parsers:
- ``ChartParser`` is a simple and flexible chart parser. Given a set of chart rules, it will apply those rules to the chart until no more edges are added.
- ``SteppingChartParser`` is a subclass of ``ChartParser`` that can be used to step through the parsing process. """
######################################################################## ## Edges ########################################################################
""" A hypothesis about the structure of part of a sentence. Each edge records the fact that a structure is (partially) consistent with the sentence. An edge contains:
- A span, indicating what part of the sentence is consistent with the hypothesized structure. - A left-hand side, specifying what kind of structure is hypothesized. - A right-hand side, specifying the contents of the hypothesized structure. - A dot position, indicating how much of the hypothesized structure is consistent with the sentence.
Every edge is either complete or incomplete:
- An edge is complete if its structure is fully consistent with the sentence. - An edge is incomplete if its structure is partially consistent with the sentence. For every incomplete edge, the span specifies a possible prefix for the edge's structure.
There are two kinds of edge:
- A ``TreeEdge`` records which trees have been found to be (partially) consistent with the text. - A ``LeafEdge`` records the tokens occurring in the text.
The ``EdgeI`` interface provides a common interface to both types of edge, allowing chart parsers to treat them in a uniform manner. """ if self.__class__ == EdgeI: raise TypeError('Edge is an abstract interface')
#//////////////////////////////////////////////////////////// # Span #////////////////////////////////////////////////////////////
""" Return a tuple ``(s, e)``, where ``tokens[s:e]`` is the portion of the sentence that is consistent with this edge's structure.
:rtype: tuple(int, int) """ raise NotImplementedError()
""" Return the start index of this edge's span.
:rtype: int """ raise NotImplementedError()
""" Return the end index of this edge's span.
:rtype: int """ raise NotImplementedError()
""" Return the length of this edge's span.
:rtype: int """ raise NotImplementedError()
#//////////////////////////////////////////////////////////// # Left Hand Side #////////////////////////////////////////////////////////////
""" Return this edge's left-hand side, which specifies what kind of structure is hypothesized by this edge.
:see: ``TreeEdge`` and ``LeafEdge`` for a description of the left-hand side values for each edge type. """ raise NotImplementedError()
#//////////////////////////////////////////////////////////// # Right Hand Side #////////////////////////////////////////////////////////////
""" Return this edge's right-hand side, which specifies the content of the structure hypothesized by this edge.
:see: ``TreeEdge`` and ``LeafEdge`` for a description of the right-hand side values for each edge type. """ raise NotImplementedError()
""" Return this edge's dot position, which indicates how much of the hypothesized structure is consistent with the sentence. In particular, ``self.rhs[:dot]`` is consistent with ``tokens[self.start():self.end()]``.
:rtype: int """ raise NotImplementedError()
""" Return the element of this edge's right-hand side that immediately follows its dot.
:rtype: Nonterminal or terminal or None """ raise NotImplementedError()
""" Return True if this edge's structure is fully consistent with the text.
:rtype: bool """ raise NotImplementedError()
""" Return True if this edge's structure is partially consistent with the text.
:rtype: bool """ raise NotImplementedError()
#//////////////////////////////////////////////////////////// # Comparisons #////////////////////////////////////////////////////////////
raise NotImplementedError()
raise NotImplementedError()
""" An edge that records the fact that a tree is (partially) consistent with the sentence. A tree edge consists of:
- A span, indicating what part of the sentence is consistent with the hypothesized tree. - A left-hand side, specifying the hypothesized tree's node value. - A right-hand side, specifying the hypothesized tree's children. Each element of the right-hand side is either a terminal, specifying a token with that terminal as its leaf value; or a nonterminal, specifying a subtree with that nonterminal's symbol as its node value. - A dot position, indicating which children are consistent with part of the sentence. In particular, if ``dot`` is the dot position, ``rhs`` is the right-hand size, ``(start,end)`` is the span, and ``sentence`` is the list of tokens in the sentence, then ``tokens[start:end]`` can be spanned by the children specified by ``rhs[:dot]``.
For more information about edges, see the ``EdgeI`` interface. """ """ Construct a new ``TreeEdge``.
:type span: tuple(int, int) :param span: A tuple ``(s, e)``, where ``tokens[s:e]`` is the portion of the sentence that is consistent with the new edge's structure. :type lhs: Nonterminal :param lhs: The new edge's left-hand side, specifying the hypothesized tree's node value. :type rhs: list(Nonterminal and str) :param rhs: The new edge's right-hand side, specifying the hypothesized tree's children. :type dot: int :param dot: The position of the new edge's dot. This position specifies what prefix of the production's right hand side is consistent with the text. In particular, if ``sentence`` is the list of tokens in the sentence, then ``okens[span[0]:span[1]]`` can be spanned by the children specified by ``rhs[:dot]``. """
def from_production(production, index): """ Return a new ``TreeEdge`` formed from the given production. The new edge's left-hand side and right-hand side will be taken from ``production``; its span will be ``(index,index)``; and its dot position will be ``0``.
:rtype: TreeEdge """ rhs=production.rhs(), dot=0)
""" Return a new ``TreeEdge`` formed from this edge. The new edge's dot position is increased by ``1``, and its end index will be replaced by ``new_end``.
:param new_end: The new end index. :type new_end: int :rtype: TreeEdge """ lhs=self._lhs, rhs=self._rhs, dot=self._dot+1)
# Accessors
# Comparisons & hashing (other._span, other.lhs(), other.rhs(), other._dot))
# String representation
return '[Edge: %s]' % self
""" An edge that records the fact that a leaf value is consistent with a word in the sentence. A leaf edge consists of:
- An index, indicating the position of the word. - A leaf, specifying the word's content.
A leaf edge's left-hand side is its leaf value, and its right hand side is ``()``. Its span is ``[index, index+1]``, and its dot position is ``0``. """ """ Construct a new ``LeafEdge``.
:param leaf: The new edge's leaf value, specifying the word that is recorded by this edge. :param index: The new edge's index, specifying the position of the word that is recorded by this edge. """
# Accessors
# Comparisons & hashing
# String representations return '[Edge: %s]' % (self)
######################################################################## ## Chart ########################################################################
""" A blackboard for hypotheses about the syntactic constituents of a sentence. A chart contains a set of edges, and each edge encodes a single hypothesis about the structure of some portion of the sentence.
The ``select`` method can be used to select a specific collection of edges. For example ``chart.select(is_complete=True, start=0)`` yields all complete edges whose start indices are 0. To ensure the efficiency of these selection operations, ``Chart`` dynamically creates and maintains an index for each set of attributes that have been selected on.
In order to reconstruct the trees that are represented by an edge, the chart associates each edge with a set of child pointer lists. A child pointer list is a list of the edges that license an edge's right-hand side.
:ivar _tokens: The sentence that the chart covers. :ivar _num_leaves: The number of tokens. :ivar _edges: A list of the edges in the chart :ivar _edge_to_cpls: A dictionary mapping each edge to a set of child pointer lists that are associated with that edge. :ivar _indexes: A dictionary mapping tuples of edge attributes to indices, where each index maps the corresponding edge attribute values to lists of edges. """ """ Construct a new chart. The chart is initialized with the leaf edges corresponding to the terminal leaves.
:type tokens: list :param tokens: The sentence that this chart will be used to parse. """ # Record the sentence token and the sentence length.
# Initialise the chart.
""" Clear the chart. """ # A list of edges contained in this chart.
# The set of child pointer lists associated with each edge.
# Indexes mapping attribute values to lists of edges # (used by select()).
#//////////////////////////////////////////////////////////// # Sentence Access #////////////////////////////////////////////////////////////
""" Return the number of words in this chart's sentence.
:rtype: int """
""" Return the leaf value of the word at the given index.
:rtype: str """
""" Return a list of the leaf values of each word in the chart's sentence.
:rtype: list(str) """ return self._tokens
#//////////////////////////////////////////////////////////// # Edge access #////////////////////////////////////////////////////////////
""" Return a list of all edges in this chart. New edges that are added to the chart after the call to edges() will *not* be contained in this list.
:rtype: list(EdgeI) :see: ``iteredges``, ``select`` """
""" Return an iterator over the edges in this chart. It is not guaranteed that new edges which are added to the chart before the iterator is exhausted will also be generated.
:rtype: iter(EdgeI) :see: ``edges``, ``select`` """
# Iterating over the chart yields its edges.
""" Return the number of edges contained in this chart.
:rtype: int """
""" Return an iterator over the edges in this chart. Any new edges that are added to the chart before the iterator is exahusted will also be generated. ``restrictions`` can be used to restrict the set of edges that will be generated.
:param span: Only generate edges ``e`` where ``e.span()==span`` :param start: Only generate edges ``e`` where ``e.start()==start`` :param end: Only generate edges ``e`` where ``e.end()==end`` :param length: Only generate edges ``e`` where ``e.length()==length`` :param lhs: Only generate edges ``e`` where ``e.lhs()==lhs`` :param rhs: Only generate edges ``e`` where ``e.rhs()==rhs`` :param next: Only generate edges ``e`` where ``e.next()==next`` :param dot: Only generate edges ``e`` where ``e.dot()==dot`` :param is_complete: Only generate edges ``e`` where ``e.is_complete()==is_complete`` :param is_incomplete: Only generate edges ``e`` where ``e.is_incomplete()==is_incomplete`` :rtype: iter(EdgeI) """ # If there are no restrictions, then return all edges.
# Find the index corresponding to the given restrictions.
# If it doesn't exist, then create it.
""" A helper function for ``select``, which creates a new index for a given set of attributes (aka restriction keys). """ # Make sure it's a valid index. raise ValueError('Bad restriction: %s' % key)
# Create the index.
# Add all existing edges to the index.
""" A helper function for ``insert``, which registers the new edge with all existing indexes. """
#//////////////////////////////////////////////////////////// # Edge Insertion #////////////////////////////////////////////////////////////
""" Add a new edge to the chart, using a pointer to the previous edge. """
""" Add a new edge to the chart, and return True if this operation modified the chart. In particular, return true iff the chart did not already contain ``edge``, or if it did not already associate ``child_pointer_lists`` with ``edge``.
:type edge: EdgeI :param edge: The new edge :type child_pointer_lists: sequence of tuple(EdgeI) :param child_pointer_lists: A sequence of lists of the edges that were used to form this edge. This list is used to reconstruct the trees (or partial trees) that are associated with ``edge``. :rtype: bool """ # Is it a new edge? # Add it to the list of edges. # Register with indexes.
# Get the set of child pointer lists for this edge. # It's a new CPL; register it, and return true.
#//////////////////////////////////////////////////////////// # Tree extraction & child pointer lists #////////////////////////////////////////////////////////////
""" Return a list of the complete tree structures that span the entire chart, and whose root node is ``root``. """
""" Return a list of the tree structures that are associated with ``edge``.
If ``edge`` is incomplete, then the unexpanded children will be encoded as childless subtrees, whose node value is the corresponding terminal or nonterminal.
:rtype: list(Tree) :note: If two trees share a common subtree, then the same Tree may be used to encode that subtree in both trees. If you need to eliminate this subtree sharing, then create a deep copy of each tree. """
""" A helper function for ``trees``.
:param memo: A dictionary used to record the trees that we've generated for each edge, so that when we see an edge more than once, we can reuse the same trees. """ # If we've seen this edge before, then reuse our old answer.
# when we're reading trees off the chart, don't use incomplete edges return trees
# Until we're done computing the trees for edge, set # memo[edge] to be empty. This has the effect of filtering # out any cyclic trees (i.e., trees that contain themselves as # descendants), because if we reach this edge via a cycle, # then it will appear that the edge doesn't generate any # trees.
# Leaf edges.
# Each child pointer list can be used to form trees. # Get the set of child choices for each child pointer. # child_choices[i] is the set of choices for the tree's # ith child. for cp in cpl]
# For each combination of children, add a tree.
# If the edge is incomplete, then extend it with "partial trees": unexpanded = [tree_class(elt,[]) for elt in edge.rhs()[edge.dot():]] for tree in trees: tree.extend(unexpanded)
# Update the memoization dictionary.
# Return the list of trees.
""" A helper function for ``_trees`` that finds the possible sets of subtrees for a new tree.
:param child_choices: A list that specifies the options for each child. In particular, ``child_choices[i]`` is a list of tokens and subtrees that can be used as the ``i``th child. """ not isinstance(child_choice, compat.string_types): # Only iterate over the child trees # if child_choice is iterable and NOT a string for child in child_choice for child_list in children_lists] else: # If child_choice is a string (or non-iterable) # then it is a leaf children_lists = [child_list+[child_choice] for child_list in children_lists]
""" Return the set of child pointer lists for the given edge. Each child pointer list is a list of edges that have been used to form this edge.
:rtype: list(list(EdgeI)) """ # Make a copy, in case they modify it.
#//////////////////////////////////////////////////////////// # Display #//////////////////////////////////////////////////////////// """ Return a pretty-printed string representation of a given edge in this chart.
:rtype: str :param width: The number of characters allotted to each index in the sentence. """
# Zero-width edges are "#" if complete, ">" if incomplete
# Spanning complete edges are "[===]"; Other edges are # "[---]" if complete, "[--->" if incomplete else:
""" Return a pretty-printed string representation of this chart's leaves. This string can be used as a header for calls to ``pp_edge``. """
else: header = ''
""" Return a pretty-printed string representation of this chart.
:param width: The number of characters allotted to each index in the sentence. :rtype: str """ if width is None: width = 50 // (self.num_leaves()+1) # sort edges: primary key=length, secondary key=start index. # (and filter out the token edges) edges = sorted([(e.length(), e.start(), e) for e in self]) edges = [e for (_,_,e) in edges]
return (self.pp_leaves(width) + '\n' + '\n'.join(self.pp_edge(edge, width) for edge in edges))
#//////////////////////////////////////////////////////////// # Display: Dot (AT&T Graphviz) #////////////////////////////////////////////////////////////
# Header s = 'digraph nltk_chart {\n' #s += ' size="5,5";\n' s += ' rankdir=LR;\n' s += ' node [height=0.1,width=0.1];\n' s += ' node [style=filled, color="lightgray"];\n'
# Set up the nodes for y in range(self.num_edges(), -1, -1): if y == 0: s += ' node [style=filled, color="black"];\n' for x in range(self.num_leaves()+1): if y == 0 or (x <= self._edges[y-1].start() or x >= self._edges[y-1].end()): s += ' %04d.%04d [label=""];\n' % (x,y)
# Add a spacer s += ' x [style=invis]; x->0000.0000 [style=invis];\n'
# Declare ranks. for x in range(self.num_leaves()+1): s += ' {rank=same;' for y in range(self.num_edges()+1): if y == 0 or (x <= self._edges[y-1].start() or x >= self._edges[y-1].end()): s += ' %04d.%04d' % (x,y) s += '}\n'
# Add the leaves s += ' edge [style=invis, weight=100];\n' s += ' node [shape=plaintext]\n' s += ' 0000.0000' for x in range(self.num_leaves()): s += '->%s->%04d.0000' % (self.leaf(x), x+1) s += ';\n\n'
# Add the edges s += ' edge [style=solid, weight=1];\n' for y, edge in enumerate(self): for x in range(edge.start()): s += (' %04d.%04d -> %04d.%04d [style="invis"];\n' % (x, y+1, x+1, y+1)) s += (' %04d.%04d -> %04d.%04d [label="%s"];\n' % (edge.start(), y+1, edge.end(), y+1, edge)) for x in range(edge.end(), self.num_leaves()): s += (' %04d.%04d -> %04d.%04d [style="invis"];\n' % (x, y+1, x+1, y+1)) s += '}\n' return s
######################################################################## ## Chart Rules ########################################################################
""" A rule that specifies what new edges are licensed by any given set of existing edges. Each chart rule expects a fixed number of edges, as indicated by the class variable ``NUM_EDGES``. In particular:
- A chart rule with ``NUM_EDGES=0`` specifies what new edges are licensed, regardless of existing edges. - A chart rule with ``NUM_EDGES=1`` specifies what new edges are licensed by a single existing edge. - A chart rule with ``NUM_EDGES=2`` specifies what new edges are licensed by a pair of existing edges.
:type NUM_EDGES: int :cvar NUM_EDGES: The number of existing edges that this rule uses to license new edges. Typically, this number ranges from zero to two. """ """ Add the edges licensed by this rule and the given edges to the chart. Return a list of the edges that were added.
:type edges: list(EdgeI) :param edges: A set of existing edges. The number of edges that should be passed to ``apply`` is specified by the ``NUM_EDGES`` class variable. :rtype: list(EdgeI) """ raise NotImplementedError()
""" Return a generator that will add edges licensed by this rule and the given edges to the chart, one at a time. Each time the generator is resumed, it will either add a new edge and yield that edge; or return.
:type edges: list(EdgeI) :param edges: A set of existing edges. The number of edges that should be passed to ``apply()`` is specified by the ``NUM_EDGES`` class variable. :rtype: iter(EdgeI) """ raise NotImplementedError()
""" Add all the edges licensed by this rule and the edges in the chart to the chart. Return a list of the edges that were added.
:rtype: list(EdgeI) """ raise NotImplementedError()
""" Return a generator that will add all edges licensed by this rule, given the edges that are currently in the chart, one at a time. Each time the generator is resumed, it will either add a new edge and yield that edge; or return.
:rtype: iter(EdgeI) """ raise NotImplementedError()
""" An abstract base class for chart rules. ``AbstractChartRule`` provides:
- A default implementation for ``apply``, based on ``apply_iter``. - A default implementation for ``apply_everywhere_iter``, based on ``apply_iter``. - A default implementation for ``apply_everywhere``, based on ``apply_everywhere_iter``. Currently, this implementation assumes that ``NUM_EDGES``<=3. - A default implementation for ``__str__``, which returns a name basd on the rule's class name. """
# Subclasses must define apply_iter. raise NotImplementedError()
# Default: loop through the given number of edges, and call # self.apply() for each set of edges.
elif self.NUM_EDGES == 2: for e1 in chart: for e2 in chart: for new_edge in self.apply_iter(chart, grammar, e1, e2): yield new_edge
elif self.NUM_EDGES == 3: for e1 in chart: for e2 in chart: for e3 in chart: for new_edge in self.apply_iter(chart,grammar,e1,e2,e3): yield new_edge
else: raise AssertionError('NUM_EDGES>3 is not currently supported')
# Default: delegate to apply_iter.
# Default: delegate to apply_everywhere_iter. return list(self.apply_everywhere_iter(chart, grammar))
# Default: return a name based on the class name. # Add spaces between InitialCapsWords. return re.sub('([a-z])([A-Z])', r'\1 \2', self.__class__.__name__)
#//////////////////////////////////////////////////////////// # Fundamental Rule #////////////////////////////////////////////////////////////
""" A rule that joins two adjacent edges to form a single combined edge. In particular, this rule specifies that any pair of edges
- ``[A -> alpha \* B beta][i:j]`` - ``[B -> gamma \*][j:k]``
licenses the edge:
- ``[A -> alpha B * beta][i:j]`` """ # Make sure the rule is applicable. if not (left_edge.is_incomplete() and right_edge.is_complete() and left_edge.end() == right_edge.start() and next(left_edge) == right_edge.lhs()): return
# Construct the new edge. new_edge = left_edge.move_dot_forward(right_edge.end())
# Insert it into the chart. if chart.insert_with_backpointer(new_edge, left_edge, right_edge): yield new_edge
""" A rule that joins a given edge with adjacent edges in the chart, to form combined edges. In particular, this rule specifies that either of the edges:
- ``[A -> alpha \* B beta][i:j]`` - ``[B -> gamma \*][j:k]``
licenses the edge:
- ``[A -> alpha B * beta][i:j]``
if the other edge is already in the chart.
:note: This is basically ``FundamentalRule``, with one edge left unspecified. """
else:
is_complete=False, next=right_edge.lhs()):
is_complete=True, lhs=next(left_edge)):
#//////////////////////////////////////////////////////////// # Inserting Terminal Leafs #////////////////////////////////////////////////////////////
#//////////////////////////////////////////////////////////// # Top-Down Prediction #////////////////////////////////////////////////////////////
""" A rule licensing edges corresponding to the grammar productions for the grammar's start symbol. In particular, this rule specifies that ``[S -> \* alpha][0:i]`` is licensed for each grammar production ``S -> alpha``, where ``S`` is the grammar's start symbol. """
""" A rule licensing edges corresponding to the grammar productions for the nonterminal following an incomplete edge's dot. In particular, this rule specifies that ``[A -> alpha \* B beta][i:j]`` licenses the edge ``[B -> \* gamma][j:j]`` for each grammar production ``B -> gamma``.
:note: This rule corresponds to the Predictor Rule in Earley parsing. """ if edge.is_complete(): return for prod in grammar.productions(lhs=next(edge)): new_edge = TreeEdge.from_production(prod, edge.end()) if chart.insert(new_edge, ()): yield new_edge
""" A cached version of ``TopDownPredictRule``. After the first time this rule is applied to an edge with a given ``end`` and ``next``, it will not generate any more edges for edges with that ``end`` and ``next``.
If ``chart`` or ``grammar`` are changed, then the cache is flushed. """
# If we've already applied this rule to an edge with the same # next & end, and the chart & grammar have not changed, then # just return (no new edges to add).
# Add all the edges indicated by the top down expand rule. # If the left corner in the predicted production is # leaf, it must match with the input.
# Record the fact that we've applied this rule.
#//////////////////////////////////////////////////////////// # Bottom-Up Prediction #////////////////////////////////////////////////////////////
""" A rule licensing any edge corresponding to a production whose right-hand side begins with a complete edge's left-hand side. In particular, this rule specifies that ``[A -> alpha \*]`` licenses the edge ``[B -> \* A beta]`` for each grammar production ``B -> A beta``. """
""" A rule licensing any edge corresponding to a production whose right-hand side begins with a complete edge's left-hand side. In particular, this rule specifies that ``[A -> alpha \*]`` licenses the edge ``[B -> A \* beta]`` for each grammar production ``B -> A beta``.
:note: This is like ``BottomUpPredictRule``, but it also applies the ``FundamentalRule`` to the resulting edge. """
""" A rule that inserts all empty productions as passive edges, in every position in the chart. """ for index in compat.xrange(chart.num_leaves() + 1): new_edge = TreeEdge.from_production(prod, index) if chart.insert(new_edge, ()): yield new_edge
######################################################################## ## Filtered Bottom Up ########################################################################
is_complete=False, next=right_edge.lhs()):
is_complete=True, lhs=next(left_edge)): end = right_edge.end() nexttoken = end < chart.num_leaves() and chart.leaf(end) if _bottomup_filter(grammar, nexttoken, left_edge.rhs(), left_edge.dot()): new_edge = left_edge.move_dot_forward(right_edge.end()) if chart.insert_with_backpointer(new_edge, left_edge, right_edge): yield new_edge
return nexttoken == _next else:
######################################################################## ## Generic Chart Parser ########################################################################
TopDownInitRule(), CachedTopDownPredictRule(), SingleEdgeFundamentalRule()] EmptyPredictRule(), BottomUpPredictRule(), SingleEdgeFundamentalRule()] EmptyPredictRule(), BottomUpPredictCombineRule(), SingleEdgeFundamentalRule()]
FilteredBottomUpPredictCombineRule(), FilteredSingleEdgeFundamentalRule()]
""" A generic chart parser. A "strategy", or list of ``ChartRuleI`` instances, is used to decide what edges to add to the chart. In particular, ``ChartParser`` uses the following algorithm to parse texts:
| Until no new edges are added: | For each *rule* in *strategy*: | Apply *rule* to any applicable edges in the chart. | Return any complete parses in the chart """ trace_chart_width=50, use_agenda=True, chart_class=Chart): """ Create a new chart parser, that uses ``grammar`` to parse texts.
:type grammar: ContextFreeGrammar :param grammar: The grammar used to parse texts. :type strategy: list(ChartRuleI) :param strategy: A list of rules that should be used to decide what edges to add to the chart (top-down strategy by default). :type trace: int :param trace: The level of tracing that should be used when parsing a text. ``0`` will generate no tracing output; and higher numbers will produce more verbose tracing output. :type trace_chart_width: int :param trace_chart_width: The default total width reserved for the chart in trace output. The remainder of each line will be used to display edges. :type use_agenda: bool :param use_agenda: Use an optimized agenda-based algorithm, if possible. :param chart_class: The class that should be used to create the parse charts. """ # If the strategy only consists of axioms (NUM_EDGES==0) and # inference rules (NUM_EDGES==1), we can use an agenda-based algorithm:
else: self._use_agenda = False
print('%s:' % rule) should_print_rule_header = False
""" Return the final parse ``Chart`` from which all possible parse trees can be extracted.
:param tokens: The sentence to be parsed :type tokens: list(str) :rtype: Chart """
# Width, for printing trace edges.
# Use an agenda-based algorithm.
# We reverse the initial agenda, since it is a stack # but chart.edges() functions as a queue.
else: # Do not use an agenda-based algorithm. edges_added = True while edges_added: edges_added = False for rule in self._strategy: new_edges = rule.apply_everywhere(chart, grammar) edges_added = len(new_edges) trace_new_edges(chart, rule, new_edges, trace, trace_edge_width)
# Return the final chart.
# Return a list of complete parses.
""" A ``ChartParser`` using a top-down parsing strategy. See ``ChartParser`` for more information. """
""" A ``ChartParser`` using a bottom-up parsing strategy. See ``ChartParser`` for more information. """ warnings.warn("BottomUpChartParser only works for ContextFreeGrammar, " "use BottomUpProbabilisticChartParser instead", category=DeprecationWarning)
""" A ``ChartParser`` using a bottom-up left-corner parsing strategy. This strategy is often more efficient than standard bottom-up. See ``ChartParser`` for more information. """
raise ValueError("LeftCornerParser only works for grammars " "without empty productions.")
######################################################################## ## Stepping Chart Parser ########################################################################
""" A ``ChartParser`` that allows you to step through the parsing process, adding a single edge at a time. It also allows you to change the parser's strategy or grammar midway through parsing a text.
The ``initialize`` method is used to start parsing a text. ``step`` adds a single edge to the chart. ``set_strategy`` changes the strategy used by the chart parser. ``parses`` returns the set of parses that has been found by the chart parser.
:ivar _restart: Records whether the parser's strategy, grammar, or chart has been changed. If so, then ``step`` must restart the parsing algorithm. """
#//////////////////////////////////////////////////////////// # Initialization #////////////////////////////////////////////////////////////
"Begin parsing the given tokens."
#//////////////////////////////////////////////////////////// # Stepping #////////////////////////////////////////////////////////////
""" Return a generator that adds edges to the chart, one at a time. Each time the generator is resumed, it adds a single edge and yields that edge. If no more edges can be added, then it yields None.
If the parser's strategy, grammar, or chart is changed, then the generator will continue adding edges using the new strategy, grammar, or chart.
Note that this generator never terminates, since the grammar or strategy might be changed to values that would add new edges. Instead, it yields None when no more edges can be added with the current strategy and grammar. """ raise ValueError('Parser must be initialized first')
else:
""" A generator that implements the actual parsing algorithm. ``step`` iterates through this generator, and restarts it whenever the parser's strategy, grammar, or chart is modified. """
#//////////////////////////////////////////////////////////// # Accessors #////////////////////////////////////////////////////////////
"Return the strategy used by this parser." return self._strategy
"Return the grammar used by this parser." return self._grammar
"Return the chart that is used by this parser."
"Return the chart rule used to generate the most recent edge." return self._current_chartrule
"Return the parse trees currently contained in the chart."
#//////////////////////////////////////////////////////////// # Parser modification #////////////////////////////////////////////////////////////
""" Change the strategy that the parser uses to decide which edges to add to the chart.
:type strategy: list(ChartRuleI) :param strategy: A list of rules that should be used to decide what edges to add to the chart. """
"Change the grammar used by the parser." if grammar is self._grammar: return self._grammar = grammar self._restart = True
"Load a given chart into the chart parser." if chart is self._chart: return self._chart = chart self._restart = True
#//////////////////////////////////////////////////////////// # Standard parser methods #////////////////////////////////////////////////////////////
tokens = list(tokens) self._grammar.check_coverage(tokens)
# Initialize ourselves. self.initialize(tokens)
# Step until no more edges are generated. for e in self.step(): if e is None: break
# Return a list of complete parses. return self.parses(tree_class=tree_class)[:n]
######################################################################## ## Demo Code ########################################################################
S -> NP VP PP -> "with" NP NP -> NP PP VP -> VP PP VP -> Verb NP VP -> Verb NP -> Det Noun NP -> "John" NP -> "I" Det -> "the" Det -> "my" Det -> "a" Noun -> "dog" Noun -> "cookie" Verb -> "ate" Verb -> "saw" Prep -> "with" Prep -> "under" """)
should_print_times=True, should_print_grammar=False, should_print_trees=True, trace=2, sent='I saw John with a dog with my cookie', numparses=5): """ A demonstration of the chart parsers. """
# The grammar for ChartParser and SteppingChartParser: print("* Grammar") print(grammar)
# Tokenize the sample sentence.
# Ask the user which parser to test, # if the parser wasn't provided as an argument print(' 1: Top-down chart parser') print(' 2: Bottom-up chart parser') print(' 3: Bottom-up left-corner chart parser') print(' 4: Left-corner chart parser with bottom-up filter') print(' 5: Stepping chart parser (alternating top-down & bottom-up)') print(' 6: All parsers') print('\nWhich parser (1-6)? ', end=' ') choice = sys.stdin.readline().strip() print()
print('Bad parser number') return
# Keep track of how long each parser takes.
'2': ('Bottom-up', BU_STRATEGY), '3': ('Bottom-up left-corner', BU_LC_STRATEGY), '4': ('Filtered left-corner', LC_STRATEGY)}
# Run the requested chart parser(s), except the stepping parser. else: print("Nr trees:", len(parses))
# Run the stepping parser, if requested. else: print("Nr trees:", len(cp.parses()))
# Print the times of all parsers: print("* Parsing times") print() maxlen = max(len(key) for key in times) format = '%' + repr(maxlen) + 's parser: %6.3fsec' times_items = times.items() times_items.sort(lambda a,b:cmp(a[1], b[1])) for (parser, t) in times_items: print(format % (parser, t))
|