
    g                     ~   d Z ddlZddlmZ ddlmZ ddlmZmZm	Z	m
Z
mZ ddlmZ ddlmZ ddlmZmZ e G d	 d
             Zd Z G d de	e      Zd Zd Ze G d d             Z G d de      Z G d dee      Z G d d      Z G d de      Ze G d d             Z G d d      Z G d d      Z G d  d!e      Z d" Z!d# Z"d$ Z#d% Z$ ejJ                  d&ejL                        Z' ejJ                  d'ejL                        Z( ejJ                  d(ejL                        Z) ejJ                  d)ejL                        Z*d9d*Z+d:d+Z, ejJ                  d,ejL                        Z-d- Z. ejJ                  d.ejL                        Z/ ejJ                  d/      Z0d0 Z1d1 Z2d2 Z3d3 Z4d4 Z5d5 Z6d6 Z7e8d7k(  r e7        g d8Z9y);a  
Basic data classes for representing context free grammars.  A
"grammar" specifies which trees can represent the structure of a
given text.  Each of these trees is called a "parse tree" for the
text (or simply a "parse").  In a "context free" grammar, the set of
parse trees for any piece of a text can depend only on that piece, and
not on the rest of the text (i.e., the piece's context).  Context free
grammars are often used to find possible syntactic structures for
sentences.  In this context, the leaves of a parse tree are word
tokens; and the node values are phrasal categories, such as ``NP``
and ``VP``.

The ``CFG`` class is used to encode context free grammars.  Each
``CFG`` consists of a start symbol and a set of productions.
The "start symbol" specifies the root node value for parse trees.  For example,
the start symbol for syntactic parsing is usually ``S``.  Start
symbols are encoded using the ``Nonterminal`` class, which is discussed
below.

A Grammar's "productions" specify what parent-child relationships a parse
tree can contain.  Each production specifies that a particular
node can be the parent of a particular set of children.  For example,
the production ``<S> -> <NP> <VP>`` specifies that an ``S`` node can
be the parent of an ``NP`` node and a ``VP`` node.

Grammar productions are implemented by the ``Production`` class.
Each ``Production`` consists of a left hand side and a right hand
side.  The "left hand side" is a ``Nonterminal`` that specifies the
node type for a potential parent; and the "right hand side" is a list
that specifies allowable children for that parent.  This lists
consists of ``Nonterminals`` and text types: each ``Nonterminal``
indicates that the corresponding child may be a ``TreeToken`` with the
specified node type; and each text type indicates that the
corresponding child may be a ``Token`` with the with that type.

The ``Nonterminal`` class is used to distinguish node values from leaf
values.  This prevents the grammar from accidentally using a leaf
value (such as the English word "A") as the node of a subtree.  Within
a ``CFG``, all node values are wrapped in the ``Nonterminal``
class. Note, however, that the trees that are specified by the grammar do
*not* include these ``Nonterminal`` wrappers.

Grammars can also be given a more procedural interpretation.  According to
this interpretation, a Grammar specifies any tree structure *tree* that
can be produced by the following procedure:

| Set tree to the start symbol
| Repeat until tree contains no more nonterminal leaves:
|   Choose a production prod with whose left hand side
|     lhs is a nonterminal leaf of tree.
|   Replace the nonterminal leaf with a subtree, whose node
|     value is the value wrapped by the nonterminal lhs, and
|     whose children are the right hand side of prod.

The operation of replacing the left hand side (*lhs*) of a production
with the right hand side (*rhs*) in a tree (*tree*) is known as
"expanding" *lhs* to *rhs* in *tree*.
    N)deque)total_ordering)SLASHTYPEFeatDict
FeatStructFeatStructReader)raise_unorderable_types)ImmutableProbabilisticMixIn)invert_graphtransitive_closurec                   L    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zy)Nonterminala.  
    A non-terminal symbol for a context free grammar.  ``Nonterminal``
    is a wrapper class for node values; it is used by ``Production``
    objects to distinguish node values from leaf values.
    The node value that is wrapped by a ``Nonterminal`` is known as its
    "symbol".  Symbols are typically strings representing phrasal
    categories (such as ``"NP"`` or ``"VP"``).  However, more complex
    symbol types are sometimes used (e.g., for lexicalized grammars).
    Since symbols are node values, they must be immutable and
    hashable.  Two ``Nonterminals`` are considered equal if their
    symbols are equal.

    :see: ``CFG``, ``Production``
    :type _symbol: any
    :ivar _symbol: The node value corresponding to this
        ``Nonterminal``.  This value must be immutable and hashable.
    c                     || _         y)z
        Construct a new non-terminal from the given symbol.

        :type symbol: any
        :param symbol: The node value corresponding to this
            ``Nonterminal``.  This value must be immutable and
            hashable.
        N_symbol)selfsymbols     A/var/www/openai/venv/lib/python3.12/site-packages/nltk/grammar.py__init__zNonterminal.__init__i   s         c                     | j                   S )ze
        Return the node value corresponding to this ``Nonterminal``.

        :rtype: (any)
        r   r   s    r   r   zNonterminal.symbolt   s     ||r   c                 f    t        |       t        |      k(  xr | j                  |j                  k(  S )z
        Return True if this non-terminal is equal to ``other``.  In
        particular, return True if ``other`` is a ``Nonterminal``
        and this non-terminal's symbol is equal to ``other`` 's symbol.

        :rtype: bool
        )typer   r   others     r   __eq__zNonterminal.__eq__|   s)     DzT%[(JT\\U]]-JJr   c                     | |k(   S N r   s     r   __ne__zNonterminal.__ne__       5=  r   c                 n    t        |t              st        d| |       | j                  |j                  k  S N<)
isinstancer   r
   r   r   s     r   __lt__zNonterminal.__lt__   s+    %-#Cu5||emm++r   c                 ,    t        | j                        S r    )hashr   r   s    r   __hash__zNonterminal.__hash__   s    DLL!!r   c                     t        | j                  t              rd| j                  z  S dt        | j                        z  S z_
        Return a string representation for this ``Nonterminal``.

        :rtype: str
        %sr'   r   strreprr   s    r   __repr__zNonterminal.__repr__   5     dllC($,,&&$t||,,,r   c                     t        | j                  t              rd| j                  z  S dt        | j                        z  S r-   r/   r   s    r   __str__zNonterminal.__str__   r3   r   c                 J    t        | j                   d|j                         S )aA  
        Return a new nonterminal whose symbol is ``A/B``, where ``A`` is
        the symbol for this nonterminal, and ``B`` is the symbol for rhs.

        :param rhs: The nonterminal used to form the right hand side
            of the new nonterminal.
        :type rhs: Nonterminal
        :rtype: Nonterminal
        /)r   r   r   rhss     r   __div__zNonterminal.__div__   s"     dll^1S[[M:;;r   c                 $    | j                  |      S )a  
        Return a new nonterminal whose symbol is ``A/B``, where ``A`` is
        the symbol for this nonterminal, and ``B`` is the symbol for rhs.
        This function allows use of the slash ``/`` operator with
        the future import of division.

        :param rhs: The nonterminal used to form the right hand side
            of the new nonterminal.
        :type rhs: Nonterminal
        :rtype: Nonterminal
        )r:   r8   s     r   __truediv__zNonterminal.__truediv__   s     ||C  r   N)__name__
__module____qualname____doc__r   r   r   r"   r(   r+   r2   r5   r:   r<   r!   r   r   r   r   U   s:    $	K!,
"	-	-
<!r   r   c                     d| v r| j                  d      }n| j                         }|D cg c]  }t        |j                                c}S c c}w )a  
    Given a string containing a list of symbol names, return a list of
    ``Nonterminals`` constructed from those symbols.

    :param symbols: The symbol name string.  This string can be
        delimited by either spaces or commas.
    :type symbols: str
    :return: A list of ``Nonterminals`` constructed from the symbol
        names given in ``symbols``.  The ``Nonterminals`` are sorted
        in the same order as the symbols names.
    :rtype: list(Nonterminal)
    ,)splitr   strip)symbolssymbol_listss      r   nonterminalsrH      sG     g~mmC(mmo,78KqK	"K888s    Ac                       e Zd ZdZd Zd Zy)FeatStructNonterminalz|A feature structure that's also a nonterminal.  It acts as its
    own symbol, and automatically freezes itself when hashed.c                 L    | j                          t        j                  |       S r    )freezer   r+   r   s    r   r+   zFeatStructNonterminal.__hash__   s    ""4((r   c                     | S r    r!   r   s    r   r   zFeatStructNonterminal.symbol   s    r   N)r=   r>   r?   r@   r+   r   r!   r   r   rJ   rJ      s    A)r   rJ   c                 "    t        | t              S )zJ
    :return: True if the item is a ``Nonterminal``.
    :rtype: bool
    )r'   r   items    r   is_nonterminalrQ      s    
 dK((r   c                 @    t        | d      xr t        | t               S )z
    Return True if the item is a terminal, which currently is
    if it is hashable and not a ``Nonterminal``.

    :rtype: bool
    r+   )hasattrr'   r   rO   s    r   is_terminalrT      s      4$JZk-J)JJr   c                   X    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zy)
Productiona  
    A grammar production.  Each production maps a single symbol
    on the "left-hand side" to a sequence of symbols on the
    "right-hand side".  (In the case of context-free productions,
    the left-hand side must be a ``Nonterminal``, and the right-hand
    side is a sequence of terminals and ``Nonterminals``.)
    "terminals" can be any immutable hashable object that is
    not a ``Nonterminal``.  Typically, terminals are strings
    representing words, such as ``"dog"`` or ``"under"``.

    :see: ``CFG``
    :see: ``DependencyGrammar``
    :see: ``Nonterminal``
    :type _lhs: Nonterminal
    :ivar _lhs: The left-hand side of the production.
    :type _rhs: tuple(Nonterminal, terminal)
    :ivar _rhs: The right-hand side of the production.
    c                 h    t        |t              rt        d      || _        t	        |      | _        y)a  
        Construct a new ``Production``.

        :param lhs: The left-hand side of the new ``Production``.
        :type lhs: Nonterminal
        :param rhs: The right-hand side of the new ``Production``.
        :type rhs: sequence(Nonterminal and terminal)
        z9production right hand side should be a list, not a stringN)r'   r0   	TypeError_lhstuple_rhs)r   lhsr9   s      r   r   zProduction.__init__  s2     c3N  	#J	r   c                     | j                   S )z`
        Return the left-hand side of this ``Production``.

        :rtype: Nonterminal
        )rY   r   s    r   r\   zProduction.lhs#       yyr   c                     | j                   S )zx
        Return the right-hand side of this ``Production``.

        :rtype: sequence(Nonterminal and terminal)
        )r[   r   s    r   r9   zProduction.rhs+  r^   r   c                 ,    t        | j                        S )zP
        Return the length of the right-hand side.

        :rtype: int
        )lenr[   r   s    r   __len__zProduction.__len__3  s     499~r   c                 :    t        d | j                  D              S )zi
        Return True if the right-hand side only contains ``Nonterminals``

        :rtype: bool
        c              3   2   K   | ]  }t        |        y wr    )rQ   ).0ns     r   	<genexpr>z+Production.is_nonlexical.<locals>.<genexpr>A  s     8i>!$i   )allr[   r   s    r   is_nonlexicalzProduction.is_nonlexical;  s     8dii888r   c                 $    | j                          S )zj
        Return True if the right-hand contain at least one terminal token.

        :rtype: bool
        )rj   r   s    r   
is_lexicalzProduction.is_lexicalC  s     %%'''r   c                     dt        | j                        z  }|dj                  d | j                  D              z  }|S )zd
        Return a verbose string representation of the ``Production``.

        :rtype: str
        z%s ->  c              3   2   K   | ]  }t        |        y wr    )r1   )re   els     r   rg   z%Production.__str__.<locals>.<genexpr>R  s     8i48irh   )r1   rY   joinr[   )r   results     r   r5   zProduction.__str__K  s8     DO+#((8dii888r   c                     d| z  S )zd
        Return a concise string representation of the ``Production``.

        :rtype: str
        r.   r!   r   s    r   r2   zProduction.__repr__U  s     d{r   c                     t        |       t        |      k(  xr4 | j                  |j                  k(  xr | j                  |j                  k(  S )za
        Return True if this ``Production`` is equal to ``other``.

        :rtype: bool
        )r   rY   r[   r   s     r   r   zProduction.__eq__]  sC     J$u+% (		UZZ'(		UZZ'	
r   c                     | |k(   S r    r!   r   s     r   r"   zProduction.__ne__i  r#   r   c                     t        |t              st        d| |       | j                  | j                  f|j                  |j                  fk  S r%   )r'   rV   r
   rY   r[   r   s     r   r(   zProduction.__lt__l  s=    %,#Cu5		499%UZZ(@@@r   c                 D    t        | j                  | j                  f      S )zR
        Return a hash value for the ``Production``.

        :rtype: int
        )r*   rY   r[   r   s    r   r+   zProduction.__hash__q  s     TYY		*++r   N)r=   r>   r?   r@   r   r\   r9   rb   rj   rl   r5   r2   r   r"   r(   r+   r!   r   r   rV   rV      sD    & 9(

!A
,r   rV   c                       e Zd ZdZd Zy)DependencyProductionz
    A dependency grammar production.  Each production maps a single
    head word to an unordered list of one or more modifier words.
    c                 Z    d| j                    d}| j                  D ]  }|d| dz  } |S )zn
        Return a verbose string representation of the ``DependencyProduction``.

        :rtype: str
        'z' ->z ')rY   r[   )r   rr   elts      r   r5   zDependencyProduction.__str__  s;     TYYKt$99C3%qk!F r   N)r=   r>   r?   r@   r5   r!   r   r   ry   ry   z  s    
	r   ry   c                   :     e Zd ZdZd Z fdZd Zd Zd Z xZ	S )ProbabilisticProductiona  
    A probabilistic context free grammar production.
    A PCFG ``ProbabilisticProduction`` is essentially just a ``Production`` that
    has an associated probability, which represents how likely it is that
    this production will be used.  In particular, the probability of a
    ``ProbabilisticProduction`` records the likelihood that its right-hand side is
    the correct instantiation for any given occurrence of its left-hand side.

    :see: ``Production``
    c                 ^    t        j                  | fi | t        j                  | ||       y)a  
        Construct a new ``ProbabilisticProduction``.

        :param lhs: The left-hand side of the new ``ProbabilisticProduction``.
        :type lhs: Nonterminal
        :param rhs: The right-hand side of the new ``ProbabilisticProduction``.
        :type rhs: sequence(Nonterminal and terminal)
        :param prob: Probability parameters of the new ``ProbabilisticProduction``.
        N)r   r   rV   )r   r\   r9   probs       r   r   z ProbabilisticProduction.__init__  s)     	$,,T:T:D#s+r   c                 v    t         |          | j                         dk(  rdz   S d| j                         z  z   S )N      ?z [1.0]z [%g])superr5   r   )r   	__class__s    r   r5   zProbabilisticProduction.__str__  s?    w +H
 	
29DIIK2G
 	
r   c                     t        |       t        |      k(  xrW | j                  |j                  k(  xr< | j                  |j                  k(  xr! | j                         |j                         k(  S r    )r   rY   r[   r   r   s     r   r   zProbabilisticProduction.__eq__  s\    J$u+% ,		UZZ',		UZZ', 		uzz|+		
r   c                     | |k(   S r    r!   r   s     r   r"   zProbabilisticProduction.__ne__  r#   r   c                 b    t        | j                  | j                  | j                         f      S r    )r*   rY   r[   r   r   s    r   r+   z ProbabilisticProduction.__hash__  s"    TYY		499;788r   )
r=   r>   r?   r@   r   r5   r   r"   r+   __classcell__)r   s   @r   r~   r~     s!    	,


!9r   r~   c                       e Zd ZdZddZd Zd Zedd       Zd Z	ddZ
d	 Zd
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddZed        Zed d       Zed        Zd Zd Zy)!CFGa#  
    A context-free grammar.  A grammar consists of a start state and
    a set of productions.  The set of terminals and nonterminals is
    implicitly specified by the productions.

    If you need efficient key-based access to productions, you
    can use a subclass to implement it.
    c                 .   t        |      s!t        dt        |      j                  z        || _        || _        |D ch c]  }|j                          c}| _        | j                          | j                          |r| j                          yyc c}w )a  
        Create a new context-free grammar, from the given start state
        and set of ``Production`` instances.

        :param start: The start symbol
        :type start: Nonterminal
        :param productions: The list of productions that defines the grammar
        :type productions: list(Production)
        :param calculate_leftcorners: False if we don't want to calculate the
            leftcorner relation. In that case, some optimized chart parsers won't work.
        :type calculate_leftcorners: bool
        z.start should be a Nonterminal object, not a %sN)rQ   rX   r   r=   _start_productionsr\   _categories_calculate_indexes_calculate_grammar_forms_calculate_leftcorners)r   startproductionscalculate_leftcornersprods        r   r   zCFG.__init__  s     e$"5k223 
 '3>?;4DHHJ;?!%%' '') ! @s   Bc                 x   i | _         i | _        i | _        i | _        | j                  D ]  }|j
                  }|| j                   vrg | j                   |<   | j                   |   j                  |       |j                  rK|j                  d   }|| j                  vrg | j                  |<   | j                  |   j                  |       n|| j                  |j                         <   |j                  D ]A  }t        |      s| j                  j                  |t                     j                  |       C  y Nr   )
_lhs_index
_rhs_index_empty_index_lexical_indexr   rY   appendr[   r\   rT   
setdefaultsetaddr   r   r\   rhs0tokens        r   r   zCFG._calculate_indexes  s     %%D))C$//)')$OOC ''-yyyy|t.,.DOOD)%,,T2 15!!$((*-u%''225#%@DDTJ #! &r   c           	         | j                   D ci c]  }||h c}| _        | j                   D ci c]  }|t                c}| _        | j	                         D ]|  }t        |      dkD  s|j                         |j                         d   }}t        |      r| j                  |   j                  |       _| j                  |   j                  |       ~ t        | j                  d      }|| _        t        |      | _        t        t        t
        | j                  j!                                     }t        t        t
        | j                  j!                                     }||cxkD  rdkD  r	d | _        y  i | _        | j                  D ]d  }| j                  |   }t               x}| j"                  |<   |D ]5  }|j%                  | j                  j'                  |t                            7 f y c c}w c c}w )Nr   T)	reflexivei'  )r    _immediate_leftcorner_categoriesr   _immediate_leftcorner_wordsr   ra   r\   r9   rQ   r   r   _leftcornersr   _leftcorner_parentssummapvalues_leftcorner_wordsupdateget)r   catr   leftlcnr_leftcorner_categoriesnr_leftcorner_wordsleftss           r   r   zCFG._calculate_leftcorners  s   GKGWGW0XGWseGW0X-BFBRBR+SBR3CJBR+S($$&D4y1} HHJ
1T!$'99#>BB4H44S9==dC '   E EQUV#/#3 #&T::AACD$
  "#c4+K+K+R+R+T"UV!9AEA &*D"	 B "$$$C%%c*E/2u4B'',		$::>>tSUKL  %3 1Y+Ss
   G8G=Nc                 >    t        |t        |      \  }} | ||      S )z
        Return the grammar instance corresponding to the input string(s).

        :param input: a grammar, either in the form of a string or as a list of strings.
        encodingread_grammarstandard_nonterm_parserclsinputr   r   r   s        r   
fromstringzCFG.fromstring  s*     **X
{ 5+&&r   c                     | j                   S )zU
        Return the start symbol of the grammar

        :rtype: Nonterminal
        )r   r   s    r   r   z	CFG.start)  s     {{r   c                    |r|rt        d      |s*|s(|s| j                  S | j                  j                         S |r@|s>|s| j                  j                  |g       S || j                  v r| j                  |   gS g S |r|s| j                  j                  |g       S | j                  j                  |g       D cg c]"  }|| j                  j                  |g       v r|$ c}S c c}w )a  
        Return the grammar productions, filtered by the left-hand side
        or the first item in the right-hand side.

        :param lhs: Only return productions with the given left-hand side.
        :param rhs: Only return productions with the given first item
            in the right-hand side.
        :param empty: Only return productions with an empty right-hand side.
        :return: A list of productions matching the given constraints.
        :rtype: list(Production)
        CYou cannot select empty and non-empty productions at the same time.)
ValueErrorr   r   r   r   r   r   r   r\   r9   emptyr   s        r   r   zCFG.productions3  s     5X 
 3(((((//11 **333)))))#.//	 ??&&sB// !OO//R88D4??..sB77 8  s   <'C&c                 <    | j                   j                  ||h      S )a  
        Return the set of all nonterminals that the given nonterminal
        can start with, including itself.

        This is the reflexive, transitive closure of the immediate
        leftcorner relation:  (A > B)  iff  (A -> B beta)

        :param cat: the parent of the leftcorners
        :type cat: Nonterminal
        :return: the set of all leftcorners
        :rtype: set(Nonterminal)
        )r   r   r   r   s     r   leftcornerszCFG.leftcorners`  s       $$S3%00r   c                      t              r j                  |      v S  j                  r& j                  j                  |t	                     v S t         fd j                  |      D              S )a-  
        True if left is a leftcorner of cat, where left can be a
        terminal or a nonterminal.

        :param cat: the parent of the leftcorner
        :type cat: Nonterminal
        :param left: the suggested leftcorner
        :type left: Terminal or Nonterminal
        :rtype: bool
        c              3   j   K   | ]*  }j                   j                  |t                     v  , y wr    )r   r   r   )re   parentr   r   s     r   rg   z$CFG.is_leftcorner.<locals>.<genexpr>  s3      3F 88<<VSUKK3s   03)rQ   r   r   r   r   any)r   r   r   s   ` `r   is_leftcornerzCFG.is_leftcornero  sq     $4++C000##41155c35AAA "..s3  r   c                 <    | j                   j                  ||h      S )aC  
        Return the set of all nonterminals for which the given category
        is a left corner. This is the inverse of the leftcorner relation.

        :param cat: the suggested leftcorner
        :type cat: Nonterminal
        :return: the set of all parents to the leftcorner
        :rtype: set(Nonterminal)
        )r   r   r   s     r   leftcorner_parentszCFG.leftcorner_parents  s     ''++C#77r   c                     |D cg c]   }| j                   j                  |      r|" }}|r&dj                  d |D              }t        d|z        yc c}w )z
        Check whether the grammar rules cover the given list of tokens.
        If not, then raise an exception.

        :type tokens: list(str)
        z, c              3   "   K   | ]  }| 	 y wr    r!   )re   ws     r   rg   z%CFG.check_coverage.<locals>.<genexpr>  s     :'Q1%'s   z3Grammar does not cover some of the input words: %r.N)r   r   rq   r   )r   tokenstokmissings       r   check_coveragezCFG.check_coverage  sb     #)M&30C0C0G0G0L3&Mii:'::GH7R   Ns
    AAc                    | j                   }t        d |D              | _        t        d |D              | _        t	        d |D              | _        t        d |D              | _        t        d |D              | _        y)z@
        Pre-calculate of which form(s) the grammar is.
        c              3   <   K   | ]  }|j                           y wr    )rl   re   ps     r   rg   z/CFG._calculate_grammar_forms.<locals>.<genexpr>  s     =u!q||~us   c              3   Z   K   | ]#  }t        |      d k7  s|j                          % yw   N)ra   rj   r   s     r   rg   z/CFG._calculate_grammar_forms.<locals>.<genexpr>  s#     !RUc!fPQk!//"3U   ++c              3   2   K   | ]  }t        |        y wr    ra   r   s     r   rg   z/CFG._calculate_grammar_forms.<locals>.<genexpr>       2EqCFErh   c              3   2   K   | ]  }t        |        y wr    r   r   s     r   rg   z/CFG._calculate_grammar_forms.<locals>.<genexpr>  r   rh   c              3   Z   K   | ]#  }t        |      d k(  s|j                          % ywr   )ra   rl   r   s     r   rg   z/CFG._calculate_grammar_forms.<locals>.<genexpr>  s"     )W%Q3q6UV;!,,.%r   N)	r   ri   _is_lexical_is_nonlexicalmin_min_lenmax_max_len_all_unary_are_lexical)r   prodss     r   r   zCFG._calculate_grammar_forms  sl     !!=u==!!RU!RR2E222E22&))W%)W&W#r   c                     | j                   S )zA
        Return True if all productions are lexicalised.
        )r   r   s    r   rl   zCFG.is_lexical  s     r   c                     | j                   S )a  
        Return True if all lexical rules are "preterminals", that is,
        unary rules which can be separated in a preprocessing step.

        This means that all productions are of the forms
        A -> B1 ... Bn (n>=0), or A -> "s".

        Note: is_lexical() and is_nonlexical() are not opposites.
        There are grammars which are neither, and grammars which are both.
        )r   r   s    r   rj   zCFG.is_nonlexical  s     """r   c                     | j                   S )zW
        Return the right-hand side length of the shortest grammar production.
        r   r   s    r   min_lenzCFG.min_len       }}r   c                     | j                   S )zV
        Return the right-hand side length of the longest grammar production.
        r   r   s    r   max_lenzCFG.max_len  r   r   c                      | j                   dkD  S )z@
        Return True if there are no empty productions.
        r   r   r   s    r   is_nonemptyzCFG.is_nonempty  s     }}q  r   c                      | j                   dk  S )z
        Return True if all productions are at most binary.
        Note that there can still be empty and unary productions.
           r   r   s    r   is_binarisedzCFG.is_binarised  s    
 }}!!r   c                 j    | j                         xr" | j                         xr | j                         S )zh
        Return True if all productions are of the forms
        A -> B C, A -> B, or A -> "s".
        )r   rj   r   r   s    r   is_flexible_chomsky_normal_formz#CFG.is_flexible_chomsky_normal_form  s/    
 !Rd&8&8&:Rt?P?P?RRr   c                 >    | j                         xr | j                  S )z
        Return True if the grammar is of Chomsky Normal Form, i.e. all productions
        are of the form A -> B C, or A -> "s".
        )r   r   r   s    r   is_chomsky_normal_formzCFG.is_chomsky_normal_form  s    
 335U$:U:UUr   c           	      >   | j                         r| S | j                  d      rt        d      | j                         D ]\  }|j                         st	        |j                               dkD  s1t        d|j                          d|j                                 t        j                  |       }t        j                  ||      }|r|S t        j                  |      }t        |j                         t        t        |j                                           }|S )z
        Returns a new Grammar that is in chomsky normal

        :param: new_token_padding
            Customise new rule formation during binarisation
        T)r   z<Grammar has Empty rules. Cannot deal with them at the momentr   zCannot handled mixed rule z => )r   r   r   rl   ra   r9   r\   r   eliminate_startbinarizeremove_unitary_rulesr   listr   )r   new_token_paddingflexiblerulestep1step2step3step4s           r   chomsky_normal_formzCFG.chomsky_normal_form  s     &&(K$'Q 
 $$&D S_q%8 0DM  ' ##D)U$56L((/EKKM4E,=,=,?(@#ABr   c                 L   g }t        g       }|j                         D ]C  }t        |      dk(  r"|j                         r|j	                  |       3|j	                  |       E |r|j                         }|j                  |j                         d         D ]k  }t        |j                         |j                               }t        |      dk7  s|j                         r|j	                  |       [|j	                  |       m |rt        |j                         |      }|S )zU
        Remove nonlexical unitary rules and convert them to
        lexical
        r   r   )r\   )r   r   ra   rj   r   popleftr9   rV   r\   rl   r   r   )r   grammarrr   unitaryr  rP   new_rule	n_grammars           r   r   zCFG.remove_unitary_rules   s     )'')D4yA~$"4"4"6t$d#	 * ??$D++
1+>%dhhj$((*=x=A%)<)<)>MM(+NN8, ?  0	r   c                 X   g }|j                         D ]  }t        |j                               dkD  r|j                         }t	        dt        |j                               dz
        D ]c  }|j                         |   }t        |j                         |z   |j                         z         }t        |||f      }	|}|j                  |	       e t        ||j                         dd       }
|j                  |
       |j                  |        t        |j                         |      }|S )z
        Convert all non-binary rules into binary by introducing
        new tokens.
        Example::

            Original:
                A => B C D
            After Conversion:
                A => B A@$@B
                A@$@B => C D
        r   r   N)r   ra   r9   r\   ranger   r   rV   r   r   r   )r   r  paddingrr   r  	left_sidektsymnew_symnew_productionlast_prdr  s               r   r   zCFG.binarize  s     '')D488:" HHJ	q#dhhj/A"56A88:a=D))*:*:*<w*F*VWG%/	D'?%KN 'IMM.1 7 &iBCAh'd# * 0	r   c                 ,   |j                         }g }d}|j                         D ]'  }||j                         v rd}|j                  |       ) |rCt	        d      }|j                  t        ||j                         g             t        ||      }|S |S )z
        Eliminate start rule in case it appears on RHS
        Example: S -> S0 S1 and S0 -> S1 S
        Then another rule S0_Sigma -> S is added
        NTS0_SIGMA)r   r   r9   r   r   rV   r   )r   r  r   rr   need_to_addr  r  s          r   r   zCFG.eliminate_start;  s     '')D
""MM$ * 
+EMM*UW]]_,=>?E6*Ir   c                 2    dt        | j                        z  S )Nz<Grammar with %d productions>ra   r   r   s    r   r2   zCFG.__repr__P  s    .T5F5F1GGGr   c                     dt        | j                        z  }|d| j                  z  z  }| j                  D ]
  }|d|z  z  } |S )NzGrammar with %d productionsz (start state = %r)z
    %s)ra   r   r   )r   rr   
productions      r   r5   zCFG.__str__S  sO    .T5F5F1GG'$++55++Jj:--F ,r   Tr    NNF)@$@F)r#  )r=   r>   r?   r@   r   r   r   classmethodr   r   r   r   r   r   r   r   rl   rj   r   r   r   r   r   r   r	  r   r   r   r2   r5   r!   r   r   r   r     s    *6K2MB 	' 	'+Z1*
8	X #!"SV:  2  @  (Hr   r   c                   J    e Zd ZdZd Zd Ze	 d
d       ZddZd Z	d Z
d	 Zy)FeatureGrammara  
    A feature-based grammar.  This is equivalent to a
    ``CFG`` whose nonterminals are all
    ``FeatStructNonterminal``.

    A grammar consists of a start state and a set of
    productions.  The set of terminals and nonterminals
    is implicitly specified by the productions.
    c                 2    t         j                  | ||       y)a@  
        Create a new feature-based grammar, from the given start
        state and set of ``Productions``.

        :param start: The start symbol
        :type start: FeatStructNonterminal
        :param productions: The list of productions that defines the grammar
        :type productions: list(Production)
        N)r   r   )r   r   r   s      r   r   zFeatureGrammar.__init__f  s     	T5+.r   c                 4   i | _         i | _        i | _        g | _        i | _        | j
                  D ]e  }| j                  |j                        }|| j                   vrg | j                   |<   | j                   |   j                  |       |j                  rZ| j                  |j                  d         }|| j                  vrg | j                  |<   | j                  |   j                  |       nV|| j                  vrg | j                  |<   | j                  |   j                  |       | j                  j                  |       |j                  D ]A  }t        |      s| j                  j                  |t                     j                  |       C h y r   )r   r   r   _empty_productionsr   r   _get_type_if_possiblerY   r   r[   rT   r   r   r   r   s        r   r   z!FeatureGrammar._calculate_indexesv  sS   "$ %%D,,TYY7C$//)')$OOC ''-yy11$))A,?t.,.DOOD)%,,T2 d///-/D%%c*!!#&--d3''..t4u%''225#%@DDTJ #' &r   Nc                     |t         t        f}|t        |t        |      }n|t	        d      t        ||j                  |      \  }} | ||      S )a  
        Return a feature structure based grammar.

        :param input: a grammar, either in the form of a string or else
        as a list of strings.
        :param features: a tuple of features (default: SLASH, TYPE)
        :param logic_parser: a parser for lambda-expressions,
        by default, ``LogicParser()``
        :param fstruct_reader: a feature structure parser
        (only if features and logic_parser is None)
        )logic_parserz8'logic_parser' and 'fstruct_reader' must not both be setr   )r   r   r	   rJ   	Exceptionr   read_partial)r   r   featuresr,  fstruct_readerr   r   r   s           r   r   zFeatureGrammar.fromstring  sp     t}H!-/lN %M  *>..
{ 5+&&r   c           	      H   |r|rt        d      |s|s|r| j                  S | j                  S |rZ|sX|r+| j                  j	                  | j                  |      g       S | j                  j	                  | j                  |      g       S |r-|s+| j                  j	                  | j                  |      g       S | j                  j	                  | j                  |      g       D cg c]1  }|| j                  j	                  | j                  |      g       v r|3 c}S c c}w )a  
        Return the grammar productions, filtered by the left-hand side
        or the first item in the right-hand side.

        :param lhs: Only return productions with the given left-hand side.
        :param rhs: Only return productions with the given first item
            in the right-hand side.
        :param empty: Only return productions with an empty right-hand side.
        :rtype: list(Production)
        r   )r   r)  r   r   r   r*  r   r   r   s        r   r   zFeatureGrammar.productions  s    5X 
 3...((( ((,,T-G-G-LbQQ**4+E+Ec+JBOO ??&&t'A'A#'FKK !OO//0J0J30OQSTTD4??..t/I/I#/NPRSS T  s   &6Dc                     t        d      )z
        Return the set of all words that the given category can start with.
        Also called the "first set" in compiler construction.
        Not implemented yetNotImplementedErrorr   s     r   r   zFeatureGrammar.leftcorners      
 ""788r   c                     t        d      )zi
        Return the set of all categories for which the given category
        is a left corner.
        r3  r4  r   s     r   r   z!FeatureGrammar.leftcorner_parents  r6  r   c                 Z    t        |t              rt        |v rt        |t                 S |S )z
        Helper function which returns the ``TYPE`` feature of the ``item``,
        if it exists, otherwise it returns the ``item`` itself
        )r'   dictr   FeatureValueType)r   rP   s     r   r*  z$FeatureGrammar._get_type_if_possible  s(    
 dD!ddl#DJ//Kr   )NNNNr"  )r=   r>   r?   r@   r   r   r$  r   r   r   r   r*  r!   r   r   r&  r&  [  s>    
/ K: TX' '>(T99r   r&  c                   4    e Zd ZdZd Zd Zd Zd Zd Zd Z	y)	r:  z
    A helper class for ``FeatureGrammars``, designed to be different
    from ordinary strings.  This is to stop the ``FeatStruct``
    ``FOO[]`` from being compare equal to the terminal "FOO".
    c                     || _         y r    _value)r   values     r   r   zFeatureValueType.__init__  s	    r   c                      d| j                   z  S )Nz<%s>r=  r   s    r   r2   zFeatureValueType.__repr__  s    ##r   c                 f    t        |       t        |      k(  xr | j                  |j                  k(  S r    )r   r>  r   s     r   r   zFeatureValueType.__eq__  s'    DzT%[(HT[[ELL-HHr   c                     | |k(   S r    r!   r   s     r   r"   zFeatureValueType.__ne__  r#   r   c                 n    t        |t              st        d| |       | j                  |j                  k  S r%   )r'   r:  r
   r>  r   s     r   r(   zFeatureValueType.__lt__
  s,    %!12#Cu5{{U\\))r   c                 ,    t        | j                        S r    )r*   r>  r   s    r   r+   zFeatureValueType.__hash__  s    DKK  r   N)
r=   r>   r?   r@   r   r2   r   r"   r(   r+   r!   r   r   r:  r:    s&    $I!*
!r   r:  c                   >    e Zd ZdZd Zed        Zd Zd Zd Z	d Z
y)	DependencyGrammarz
    A dependency grammar.  A DependencyGrammar consists of a set of
    productions.  Each production specifies a head/modifier relationship
    between a pair of words.
    c                     || _         y)z
        Create a new dependency grammar, from the set of ``Productions``.

        :param productions: The list of productions that defines the grammar
        :type productions: list(Production)
        N)r   )r   r   s     r   r   zDependencyGrammar.__init__  s     (r   c                 >   g }t        |j                  d            D ];  \  }}|j                         }|j                  d      s|dk(  r-	 |t	        |      z  }= t        |      dk(  rt        d       | |      S # t
        $ r}t        d| d|       |d }~ww xY w)N
# Unable to parse line : r   No productions found!)	enumeraterC   rD   
startswith_read_dependency_productionr   ra   )r   r   r   linenumlinees         r   r   zDependencyGrammar.fromstring#  s    &u{{4'89MGT::<Ds#trzS:4@@ : {q 455;	  S #8	D6!JKQRRSs   A<<	BBBc                 x    | j                   D ]+  }|j                  D ]  }|j                  |k(  s||k(  s  y - y)a.  
        :param head: A head word.
        :type head: str
        :param mod: A mod word, to test as a modifier of 'head'.
        :type mod: str

        :return: true if this ``DependencyGrammar`` contains a
            ``DependencyProduction`` mapping 'head' to 'mod'.
        :rtype: bool
        TFr   r[   rY   r   headmodr   possibleMods        r   containszDependencyGrammar.contains2  =     ++J)??d*{c/A  / , r   c                 l    	 |\  }}| j                  ||      S # t         $ r}t        d      |d}~ww xY w)a'  
        Return True if this ``DependencyGrammar`` contains a
        ``DependencyProduction`` mapping 'head' to 'mod'.

        :param head_mod: A tuple of a head word and a mod word,
            to test as a modifier of 'head'.
        :type head: Tuple[str, str]
        :rtype: bool
        z>Must use a tuple of strings, e.g. `('price', 'of') in grammar`N)r   r[  )r   head_modrX  rY  rT  s        r   __contains__zDependencyGrammar.__contains__C  sH    	 ID#
 }}T3''	  	P	s    	3.3c                 h    dt        | j                        z  }| j                  D ]
  }|d|z  z  } |S )zj
        Return a verbose string representation of the ``DependencyGrammar``

        :rtype: str
        &Dependency grammar with %d productions
  %sr  )r   r0   r   s      r   r5   zDependencyGrammar.__str__`  s=     7T=N=N9OO++J8j((C ,
r   c                 2    dt        | j                        z  S )zU
        Return a concise string representation of the ``DependencyGrammar``
        ra  r  r   s    r   r2   zDependencyGrammar.__repr__k  s     8#d>O>O:PPPr   N)r=   r>   r?   r@   r   r$  r   r[  r_  r5   r2   r!   r   r   rF  rF    s5    (    "(:	Qr   rF  c                   (    e Zd ZdZd Zd Zd Zd Zy)ProbabilisticDependencyGrammarrn   c                 .    || _         || _        || _        y r    )r   _events_tags)r   r   eventstagss       r   r   z'ProbabilisticDependencyGrammar.__init__u  s    '
r   c                 x    | j                   D ]+  }|j                  D ]  }|j                  |k(  s||k(  s  y - y)a(  
        Return True if this ``DependencyGrammar`` contains a
        ``DependencyProduction`` mapping 'head' to 'mod'.

        :param head: A head word.
        :type head: str
        :param mod: A mod word, to test as a modifier of 'head'.
        :type mod: str
        :rtype: bool
        TFrV  rW  s        r   r[  z'ProbabilisticDependencyGrammar.containsz  r\  r   c                     dt        | j                        z  }| j                  D ]
  }|d|z  z  } |dz  }| j                  D ]  }|d| j                  |   |fz  z  } |dz  }| j                  D ]  }|d| d| j                  |    dz  } |S )	zw
        Return a verbose string representation of the ``ProbabilisticDependencyGrammar``

        :rtype: str
        z2Statistical dependency grammar with %d productionsrb  z
Events:z
  %d:%sz
Tags:z
 z:	())ra   r   rg  rh  )r   r0   r   eventtag_words        r   r5   z&ProbabilisticDependencyGrammar.__str__  s     CSF
 
 ++J8j((C ,{\\E;$,,u"5u!===C "y

HS
$tzz(';&<A>>C #
r   c                 2    dt        | j                        z  S )zb
        Return a concise string representation of the ``ProbabilisticDependencyGrammar``
        z2Statistical Dependency grammar with %d productionsr  r   s    r   r2   z'ProbabilisticDependencyGrammar.__repr__  s#     DcG
 
 	
r   N)r=   r>   r?   r@   r   r[  r5   r2   r!   r   r   re  re  r  s    
"&
r   re  c                   .    e Zd ZdZdZddZedd       Zy)PCFGa  
    A probabilistic context-free grammar.  A PCFG consists of a
    start state and a set of productions with probabilities.  The set of
    terminals and nonterminals is implicitly specified by the productions.

    PCFG productions use the ``ProbabilisticProduction`` class.
    ``PCFGs`` impose the constraint that the set of productions with
    any given left-hand-side must have probabilities that sum to 1
    (allowing for a small margin of error).

    If you need efficient key-based access to productions, you can use
    a subclass to implement it.

    :type EPSILON: float
    :cvar EPSILON: The acceptable margin of error for checking that
        productions with a given left-hand side have probabilities
        that sum to 1.
    g{Gz?c                 t   t         j                  | |||       i }|D ]D  }|j                  |j                         d      |j	                         z   ||j                         <   F |j                         D ]B  \  }}dt        j                  z
  |cxk  rdt        j                  z   k  r4n t        d|z         y)a  
        Create a new context-free grammar, from the given start state
        and set of ``ProbabilisticProductions``.

        :param start: The start symbol
        :type start: Nonterminal
        :param productions: The list of productions that defines the grammar
        :type productions: list(Production)
        :raise ValueError: if the set of productions with any left-hand-side
            do not have probabilities that sum to a value within
            EPSILON of 1.
        :param calculate_leftcorners: False if we don't want to calculate the
            leftcorner relation. In that case, some optimized chart parsers won't work.
        :type calculate_leftcorners: bool
        r   r   z"Productions for %r do not sum to 1N)	r   r   r   r\   r   itemsrr  EPSILONr   )r   r   r   r   probsr   r\   r   s           r   r   zPCFG.__init__  s      	T5+/DE %J&+ii
0@!&DzGX&XE*.."# &kkmFC%?a$,,.>? !E!KLL $r   Nc                 @    t        |t        d|      \  }} | ||      S )z
        Return a probabilistic context-free grammar corresponding to the
        input string(s).

        :param input: a grammar, either in the form of a string or else
             as a list of strings.
        T)probabilisticr   r   r   s        r   r   zPCFG.fromstring  s,     **$
{ 5+&&r   r!  r    )r=   r>   r?   r@   ru  r   r$  r   r!   r   r   rr  rr    s(    & GM4 ' 'r   rr  c                 n   i }i }|D ]N  }|j                  |j                         d      dz   ||j                         <   |j                  |d      dz   ||<   P |D cg c]C  }t        |j                         |j                         ||   ||j                            z        E }}t	        | |      S c c}w )a  
    Induce a PCFG grammar from a list of productions.

    The probability of a production A -> B C in a PCFG is:

    |                count(A -> B C)
    |  P(B, C | A) = ---------------       where \* is any right hand side
    |                 count(A -> \*)

    :param start: The start symbol
    :type start: Nonterminal
    :param productions: The list of productions that defines the grammar
    :type productions: list(Production)
    r   r   r   )r   r\   r~   r9   rr  )r   r   pcountlcountr   r   r   s          r   induce_pcfgr}    s      F F#ZZ
A6:txxzzz$*Q.t  A 	 vay6!%%'?7RS 
  u	s   AB2c                 "    t        | t              S )z8
    Return a list of context-free ``Productions``.
    _read_productionr   r   s    r   _read_cfg_productionr    s     E#:;;r   c                 &    t        | t        d      S )z=
    Return a list of PCFG ``ProbabilisticProductions``.
    T)rx  r  r  s    r   _read_pcfg_productionr    s     E#:$OOr   c                     t        | |      S )z9
    Return a list of feature-based ``Productions``.
    )r  )r   r0  s     r   _read_fcfg_productionr     s     E>22r   z
\s* -> \s*z( \[ [\d\.]+ \] ) \s*z( "[^"]*" | \'[^\']*\' ) \s*z\| \s*c           	         d} || |      \  }}t         j                  | |      }|st        d      |j                         }dg}g g}|t	        |       k  rFt
        j                  | |      }|rL|rJ|j                         }t        |j                  d      dd       |d<   |d   dkD  rt        d|d   fz        | |   dv rZt        j                  | |      }|st        d	      |d   j                  |j                  d      dd        |j                         }nq| |   d
k(  rIt        j                  | |      }|j                  d       |j                  g        |j                         }n  || |      \  }}|d   j                  |       |t	        |       k  rF|r+t        ||      D 	
cg c]  \  }	}
t        ||	|
       c}
}	S |D 	cg c]  }	t        ||	       c}	S c c}
}	w c c}	w )zX
    Parse a grammar rule, given as a string, and return
    a list of productions.
    r   zExpected an arrowg        r   r   z9Production probability %f, should not be greater than 1.0'"zUnterminated string|rz  )	_ARROW_REmatchr   endra   _PROBABILITY_REfloatgroup_TERMINAL_REr   _DISJUNCTION_REzipr~   rV   )rS  nonterm_parserrx  posr\   mprobabilitiesrhsidesnontermr9   probabilitys              r   r  r  /  s   
 C dC(HC 	c"A,--
%%'C EMdG
D	/!!$,Q%%'C %aggaj2&6 7M"R 3& 58Eb8I7KL  #Y%""4-A !677BKqwwqz!B/0%%'C #Y#%%dC0A  %NN2%%'C *$4LGSBKw'= D	/@  '*'=&A
&A"k $C;?&A
 	

 188
3$88

 9s   .G$G*c           
         || j                  |      } t        | t              r| j                  d      }n| }d}g }d}t	        |      D ]  \  }}	||	j                         z   }	|	j                  d      s|	dk(  r0|	j                  d      r|	dd j                         dz   }Xd}	 |	d   d	k(  rM|	d
d j                  dd
      \  }
}|
dk(  r% ||d      \  }}|t        |      k7  r&t        d      t        d      |t        |	||      z  } |st        d      |s|d   j                         }||fS # t        $ r}t        d|d
z    d|	 d|       |d}~ww xY w)a7  
    Return a pair consisting of a starting category and a list of
    ``Productions``.

    :param input: a grammar, either in the form of a string or else
        as a list of strings.
    :param nonterm_parser: a function for parsing nonterminals.
        It should take a ``(string, position)`` as argument and
        return a ``(nonterminal, position)`` as result.
    :param probabilistic: are the grammar rules probabilistic?
    :type probabilistic: bool
    :param encoding: the encoding of the grammar, if it is a binary string
    :type encoding: str
    NrI  rK  rJ  \r  rn   r   %r   r   zBad argument to start directivezBad directiverL  rM  rN  )decoder'   r0   rC   rO  rD   rP  endswithrstripra   r   r  r\   )r   r  rx  r   linesr   r   continue_linerR  rS  	directiveargsr  rT  s                 r   r   r   p  s    X&%D!EKM"5)tzz|+??342:== "I,,.4M	XAw#~"&qr(..q"9	4'!/a!8JE3c$i'()JKK$_55 /nmTT' *. 011A""$;  	X4Wq[MD6A3OPVWW	Xs   $A%D11	E:EEz( [\w/][\w/^<>-]* ) \s*c                     t         j                  | |      }|st        d| |d  z         t        |j	                  d            |j                         fS )NzExpected a nonterminal, found: r   )_STANDARD_NONTERM_REr  r   r   r  r  )stringr  r  s      r   r   r     sL    ""63/A:VCD\IJJ
#QUUW--r   aH  ^\s*                # leading whitespace
                              ('[^']+')\s*        # single-quoted lhs
                              (?:[-=]+>)\s*        # arrow
                              (?:(                 # rhs:
                                   "[^"]+"         # doubled-quoted terminal
                                 | '[^']+'         # single-quoted terminal
                                 | \|              # disjunction
                                 )
                                 \s*)              # trailing space
                                 *$z"('[^']'|[-=]+>|"[^"]+"|'[^']+'|\|)c                    t         j                  |       st        d      t        j	                  |       }t        |      D cg c]  \  }}|dz  dk(  s| }}}|d   j                  d      }g g}|dd  D ]<  }|dk(  r|j                  g        |d   j                  |j                  d             > |D cg c]  }t        ||       c}S c c}}w c c}w )NzBad production stringr   r   r   r  r  r  )	_READ_DG_REr  r   _SPLIT_DG_RErC   rO  rD   r   ry   )rG   piecesir   lhsider  piecerhsides           r   rQ  rQ    s    Q011"F%f-<-DAqQ!a-F<AY__U#FdGC<NN2BKu{{512	 
 @GGwV 0wGG = Hs   CC;Cc                  *   ddl m} m}m}  |d      \  }}}} |d      \  }}}	}
||z  }t	        d|||||||	|
||z  g	       t	        dt        |j                                      t	                t	         |||g             | j                  d      }t	        dt        |             t	        d	t        |j                                      t	        d
d       t	        t        |j                               j                  dd             t	                y)zG
    A demonstration showing how ``CFGs`` can be created and used.
    r   )r   rV   rH   zS, NP, VP, PPzN, V, P, DetzSome nonterminals:z    S.symbol() =>z
      S -> NP VP
      PP -> P NP
      NP -> Det N | NP PP
      VP -> V NP | VP PP
      Det -> 'a' | 'the'
      N -> 'dog' | 'cat'
      V -> 'chased' | 'sat'
      P -> 'on' | 'in'
    z
A Grammar:    grammar.start()       =>    grammar.productions() =>rn   r  rB   z,
                         N)nltkr   rV   rH   printr1   r   r   r   r   replace)r   rV   rH   SNPVPPPNVPDetVP_slash_NPr  s                r   cfg_demor    s    
 32 !1MAr2r/LAq!Sr'K	
BB1ab2g FG	
tAHHJ/0	G	*Q
 nn		G 
,W&	
($w}}*?@	
(c2	$w""$
%
-
-c3C
DE	Gr   c                     ddl m} m} ddlm} ddlm} t        j                  d      }t        j                  d      }|j                         }|d   }t        dt        |             t        d	t        |j                                      t        d
t        |j                                      t        dt        |j                                      t                |}t        dt        |             t        dt        |j                                      t        dd       t        t        |j                               j!                  dd             t                t        d       g }	|j"                  d   }
|j%                  |
      dd D ]9  }|j'                  d       |j)                  d       |	|j                         z  }	; t+        d      } | ||	      }t        |       t                t        d       |j-                  |      }|j/                  d       |j%                  |
      d   j1                         }t        |       |j3                  |      D ]  }t        |        y)zI
    A demonstration showing how a ``PCFG`` can be created and used.
    r   )r}  treetransforms)treebank)pcharta[  
        S -> NP VP [1.0]
        NP -> Det N [0.5] | NP PP [0.25] | 'John' [0.1] | 'I' [0.15]
        Det -> 'the' [0.8] | 'my' [0.2]
        N -> 'man' [0.5] | 'telescope' [0.5]
        VP -> VP PP [0.1] | V NP [0.7] | V [0.2]
        V -> 'ate' [0.35] | 'saw' [0.65]
        PP -> P NP [1.0]
        P -> 'with' [0.61] | 'under' [0.39]
        aD  
        S    -> NP VP         [1.0]
        VP   -> V NP          [.59]
        VP   -> V             [.40]
        VP   -> VP PP         [.01]
        NP   -> Det N         [.41]
        NP   -> Name          [.28]
        NP   -> NP PP         [.31]
        PP   -> P NP          [1.0]
        V    -> 'saw'         [.21]
        V    -> 'ate'         [.51]
        V    -> 'ran'         [.28]
        N    -> 'boy'         [.11]
        N    -> 'cookie'      [.12]
        N    -> 'table'       [.13]
        N    -> 'telescope'   [.14]
        N    -> 'hill'        [.5]
        Name -> 'Jack'        [.52]
        Name -> 'Bob'         [.48]
        P    -> 'with'        [.61]
        P    -> 'under'       [.39]
        Det  -> 'the'         [.41]
        Det  -> 'a'           [.31]
        Det  -> 'my'          [.28]
        r   zA PCFG production:z    pcfg_prod.lhs()  =>z    pcfg_prod.rhs()  =>z    pcfg_prod.prob() =>zA PCFG grammar:r  r  rn   r  rB   z,
                          z'Induce PCFG grammar from treebank data:N   F)collapsePOS)
horzMarkovr  z%Parse sentence using induced grammar:)r  r}  r  nltk.corpusr  
nltk.parser  rr  r   r   r  r1   r\   r9   r   r   r  _fileidsparsed_sentscollapse_unaryr	  r   InsideChartParsertraceleavesparse)r}  r  r  r  	toy_pcfg1	toy_pcfg2
pcfg_prods	pcfg_prodr  r   rP   treer  parsersentr  s                   r   	pcfg_demor    s   
 1$!		I 	I8 &&(J1I	
Y0	
#T)--/%:;	
#T)--/%:;	
#T)..*:%;<	GG	
T']+	
($w}}*?@	
(c2	$w""$
%
-
-c3C
DE	G 

34KQD%%d+BQ/.  A .t'')) 0 	CA![)G	'N	G	
12%%g.F
LLO
   &q)002D	$Kd#e $r   c                  l    dd l } | j                  j                  d      }t        |       t                y )Nr   z!grammars/book_grammars/feat0.fcfg)	nltk.datadataloadr  )r  gs     r   	fcfg_demor  c  s$    		:;A	!H	Gr   c                  D    t         j                  d      } t        |        y)z]
    A demonstration showing the creation and inspection of a
    ``DependencyGrammar``.
    zP
    'scratch' -> 'cats' | 'walls'
    'walls' -> 'the'
    'cats' -> 'the'
    N)rF  r   r  )r  s    r   dg_demor  k  s"    
  **	G 
'Nr   c                  r    ddl m}   | d      }|j                         }t        |j	                                y)zg
    A demonstration of how to read a string representation of
    a CoNLL format dependency tree.
    r   )DependencyGraphag  
    1   Ze                ze                Pron  Pron  per|3|evofmv|nom                 2   su      _  _
    2   had               heb               V     V     trans|ovt|1of2of3|ev             0   ROOT    _  _
    3   met               met               Prep  Prep  voor                             8   mod     _  _
    4   haar              haar              Pron  Pron  bez|3|ev|neut|attr               5   det     _  _
    5   moeder            moeder            N     N     soort|ev|neut                    3   obj1    _  _
    6   kunnen            kan               V     V     hulp|ott|1of2of3|mv              2   vc      _  _
    7   gaan              ga                V     V     hulp|inf                         6   vc      _  _
    8   winkelen          winkel            V     V     intrans|inf                      11  cnj     _  _
    9   ,                 ,                 Punc  Punc  komma                            8   punct   _  _
    10  zwemmen           zwem              V     V     intrans|inf                      11  cnj     _  _
    11  of                of                Conj  Conj  neven                            7   vc      _  _
    12  terrassen         terras            N     N     soort|mv|neut                    11  cnj     _  _
    13  .                 .                 Punc  Punc  punt                             12  punct   _  _
    N)r  r  r  r  pprint)r  dgr  s      r   sdg_demor  z  s1    
 +		
B" 779D	$++-r   c                  h    t                t                t                t                t	                y r    )r  r  r  r  r  r!   r   r   demor    s    JKKIJr   __main__)r   rH   r   rV   rr  r~   rF  ry   re  r}  r   )F)FN):r@   recollectionsr   	functoolsr   nltk.featstructr   r   r   r   r	   nltk.internalsr
   nltk.probabilityr   	nltk.utilr   r   r   rH   rJ   rQ   rT   rV   ry   r~   r   r&  r:  rF  re  rr  r}  r  r  r  compileVERBOSEr  r  r  r  r  r   r  r   r  r  rQ  r  r  r  r  r  r  r=   __all__r!   r   r   <module>r     s  9t 
  $ O O 2 8 6 i! i! i!X9(	Hk 	)K x, x, x,v: $*9j*E *9dZ ZzXS Xv ! ! !8\Q \Q~2
 2
j<'3 <'LJ<P3 BJJ}bjj1	"**5rzzBrzz92::F"**Y

399B4 n "rzz"<bjjI . bjj	' JJ rzzCDH(%P_D8 zFr   