³ņ
3ŅĒIc           @   sŗ  d  Z  d d k Z d d k l Z d d k l Z d d k l Z l Z l	 Z	 l
 Z
 l Z d e f d     YZ d   Z d	 e f d
     YZ d e f d     YZ d e e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d e f d     YZ d   Z d   Z d   Z d   Z d   Z e d  Z e d  Z d    Z e d!  d"    Z  d# e e f d$     YZ! d%   Z" d d d d&  Z$ e i% d' e i&  Z' e i% d(  Z( d)   Z) d*   Z* d+   Z+ e d,  Z, e d-  Z- d.   Z. d/   Z/ d0   Z0 d1   Z1 d2   Z2 e3 d3 j o e2   n d d4 d	 d d d d d d d5 d6 d7 d8 d9 d: d; d< d= d> d? d@ dA dB dC dD dE dF g Z4 d S(G   s  
Basic data classes for representing context free grammars.  A
X{grammar} specifies which trees can represent the structure of a
given text.  Each of these trees is called a X{parse tree} for the
text (or simply a X{parse}).  In a X{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 C{NP}
and C{VP}.

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

A Grammar's X{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 C{<S> -> <NP> <VP>} specifies that an C{S} node can
be the parent of an C{NP} node and a C{VP} node.

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

The C{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 C{ContextFreeGrammar}, all node values are wrapped in the C{Nonterminal} class.
Note, however, that the trees that are specified by the grammar do
B{not} include these C{Nonterminal} wrappers.

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

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

The operation of replacing the left hand side (M{lhs}) of a production
with the right hand side (M{rhs}) in a tree (M{tree}) is known as
X{expanding} M{lhs} to M{rhs} in M{tree}.
i’’’’N(   t
   deprecated(   t   ImmutableProbabilisticMixIn(   t
   FeatStructt   FeatDictt   FeatStructParsert   SLASHt   TYPEt   Nonterminalc           B   s_   e  Z d  Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z	 d   Z
 d	   Z RS(
   s:  
    A non-terminal symbol for a context free grammar.  C{Nonterminal}
    is a wrapper class for node values; it is used by
    C{Production}s to distinguish node values from leaf values.
    The node value that is wrapped by a C{Nonterminal} is known as its
    X{symbol}.  Symbols are typically strings representing phrasal
    categories (such as C{"NP"} or C{"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 C{Nonterminal}s are considered equal if their
    symbols are equal.

    @see: L{ContextFreeGrammar}
    @see: L{Production}
    @type _symbol: (any)
    @ivar _symbol: The node value corresponding to this
        C{Nonterminal}.  This value must be immutable and hashable. 
    c         C   s   | |  _  t |  |  _ d S(   só   
        Construct a new non-terminal from the given symbol.

        @type symbol: (any)
        @param symbol: The node value corresponding to this
            C{Nonterminal}.  This value must be immutable and
            hashable. 
        N(   t   _symbolt   hasht   _hash(   t   selft   symbol(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __init__f   s    		c         C   s   |  i  S(   sf   
        @return: The node value corresponding to this C{Nonterminal}. 
        @rtype: (any)
        (   R   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   r   s    c         C   sE   y' |  i  | i  j o t | |  i  SWn t j
 o t Sn Xd S(   s  
        @return: True if this non-terminal is equal to C{other}.  In
            particular, return true iff C{other} is a C{Nonterminal}
            and this non-terminal's symbol is equal to C{other}'s
            symbol.
        @rtype: C{boolean}
        N(   R   t
   isinstancet	   __class__t   AttributeErrort   False(   R   t   other(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __eq__y   s
    c         C   s   |  | j S(   s  
        @return: True if this non-terminal is not equal to C{other}.  In
            particular, return true iff C{other} is not a C{Nonterminal}
            or this non-terminal's symbol is not equal to C{other}'s
            symbol.
        @rtype: C{boolean}
        (    (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __ne__   s    c         C   s)   y t  |  i | i  SWn d Sn Xd  S(   Ni’’’’(   t   cmpR   (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __cmp__   s    c         C   s   |  i  S(   N(   R
   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __hash__   s    c         C   s7   t  |  i t  o d |  i f Sn d |  i f Sd S(   se   
        @return: A string representation for this C{Nonterminal}.
        @rtype: C{string}
        s   %ss   %rN(   R   R   t
   basestring(   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __repr__   s    c         C   s7   t  |  i t  o d |  i f Sn d |  i f Sd S(   se   
        @return: A string representation for this C{Nonterminal}.
        @rtype: C{string}
        s   %ss   %rN(   R   R   R   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __str__¤   s    c         C   s   t  d |  i | i f  S(   sa  
        @return: A new nonterminal whose symbol is C{M{A}/M{B}}, where
            C{M{A}} is the symbol for this nonterminal, and C{M{B}}
            is the symbol for rhs.
        @rtype: L{Nonterminal}
        @param rhs: The nonterminal used to form the right hand side
            of the new nonterminal.
        @type rhs: L{Nonterminal}
        s   %s/%s(   R   R   (   R   t   rhs(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __div__®   s    
(   t   __name__t
   __module__t   __doc__R   R   R   R   R   R   R   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   S   s   				
			
	
c         C   sW   d |  j o |  i  d  } n |  i    } g  } | D] } | t | i    q7 ~ S(   sź  
    Given a string containing a list of symbol names, return a list of
    C{Nonterminals} constructed from those symbols.  

    @param symbols: The symbol name string.  This string can be
        delimited by either spaces or commas.
    @type symbols: C{string}
    @return: A list of C{Nonterminals} constructed from the symbol
        names given in C{symbols}.  The C{Nonterminals} are sorted
        in the same order as the symbols names.
    @rtype: C{list} of L{Nonterminal}
    t   ,(   t   splitR   t   strip(   t   symbolst   symbol_listt   _[1]t   s(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   nonterminalsŗ   s     t
   Productionc           B   s_   e  Z d  Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z	 d   Z
 d	   Z RS(
   s  
    A grammar production.  Each production maps a single symbol
    on the X{left-hand side} to a sequence of symbols on the
    X{right-hand side}.  (In the case of context-free productions,
    the left-hand side must be a C{Nonterminal}, and the right-hand
    side is a sequence of terminals and C{Nonterminals}.)
    X{terminals} can be any immutable hashable object that is
    not a C{Nonterminal}.  Typically, terminals are strings
    representing words, such as C{"dog"} or C{"under"}.

    @see: L{ContextFreeGrammar}
    @see: L{DependencyGrammar}
    @see: L{Nonterminal}
    @type _lhs: L{Nonterminal}
    @ivar _lhs: The left-hand side of the production.
    @type _rhs: C{tuple} of (C{Nonterminal} and (terminal))
    @ivar _rhs: The right-hand side of the production.
    c         C   s]   t  | t t f  o t d   n | |  _ t |  |  _ t |  i |  i f  |  _ d S(   s  
        Construct a new C{Production}.

        @param lhs: The left-hand side of the new C{Production}.
        @type lhs: L{Nonterminal}
        @param rhs: The right-hand side of the new C{Production}.
        @type rhs: sequence of (C{Nonterminal} and (terminal))
        s9   production right hand side should be a list, not a stringN(	   R   t   strt   unicodet	   TypeErrort   _lhst   tuplet   _rhsR	   R
   (   R   t   lhsR   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   ć   s
    		c         C   s   |  i  S(   sc   
        @return: the left-hand side of this C{Production}.
        @rtype: L{Nonterminal}
        (   R,   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR/   ó   s    c         C   s   |  i  S(   s   
        @return: the right-hand side of this C{Production}.
        @rtype: sequence of (C{Nonterminal} and (terminal))
        (   R.   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   ś   s    c         C   s^   d |  i  f } xG |  i D]< } t | t  o | d | f 7} q | d | f 7} q W| S(   sv   
        @return: A verbose string representation of the
            C{Production}.
        @rtype: C{string}
        s   %s ->s    %ss    %r(   R,   R.   R   R   (   R   R)   t   elt(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s    
 c         C   s   d |  S(   sw   
        @return: A concise string representation of the
            C{Production}. 
        @rtype: C{string}
        s   %s(    (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s    c         C   s6   t  | |  i  o# |  i | i j o |  i | i j S(   sf   
        @return: true if this C{Production} is equal to C{other}.
        @rtype: C{boolean}
        (   R   R   R,   R.   (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s    c         C   s   |  | j S(   N(    (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR      s    c         C   s@   t  | |  i  p d Sn t |  i |  i f | i | i f  S(   Ni’’’’(   R   R   R   R,   R.   (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   #  s    c         C   s   |  i  S(   sU   
        @return: A hash value for the C{Production}.
        @rtype: C{int}
        (   R
   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   '  s    (   R   R   R   R   R/   R   R   R   R   R   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR(   Ļ   s   									t   DependencyProductionc           B   s   e  Z d  Z d   Z RS(   s   
    A dependency grammar production.  Each production maps a single
    head word to an unordered list of one or more modifier words.
    c         C   s9   d |  i  f } x" |  i D] } | d | f 7} q W| S(   s   
        @return: A verbose string representation of the 
            C{DependencyProduction}.
        @rtype: C{string}
        s   '%s' ->s    '%s'(   R,   R.   (   R   R)   R0   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   4  s
    
 (   R   R   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR1   /  s   t   WeightedProductionc           B   s;   e  Z d  Z d   Z d   Z d   Z d   Z d   Z RS(   sļ  
    A probabilistic context free grammar production.
    PCFG C{WeightedProduction}s are essentially just C{Production}s that
    have probabilities associated with them.  These probabilities are
    used to record how likely it is that a given production will
    be used.  In particular, the probability of a C{WeightedProduction}
    records the likelihood that its right-hand side is the correct
    instantiation for any given occurance of its left-hand side.

    @see: L{Production}
    c         K   s'   t  i |  |  t i |  | |  d S(   s{  
        Construct a new C{WeightedProduction}.

        @param lhs: The left-hand side of the new C{WeightedProduction}.
        @type lhs: L{Nonterminal}
        @param rhs: The right-hand side of the new C{WeightedProduction}.
        @type rhs: sequence of (C{Nonterminal} and (terminal))
        @param prob: Probability parameters of the new C{WeightedProduction}.
        N(   R   R   R(   (   R   R/   R   t   prob(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   M  s    
c         C   s   t  i |   d |  i   S(   Ns    [%s](   R(   R   R3   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   Z  s    c         C   sO   t  | |  i  o< |  i | i j o) |  i | i j o |  i   | i   j S(   N(   R   R   R,   R.   R3   (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   ]  s    c         C   s   |  | j S(   N(    (   R   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   c  s    c         C   s   t  |  i |  i |  i   f  S(   N(   R	   R,   R.   R3   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   f  s    (   R   R   R   R   R   R   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR2   A  s   				t   ContextFreeGrammarc           B   sS   e  Z d  Z d   Z d   Z e e d  Z d   Z d   Z d   Z	 d   Z
 RS(   s#  
    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         C   sÜ   | |  _  | |  _ h  |  _ h  |  _ x± |  i D]¦ } | i |  i j o g  |  i | i <n | i o/ | i d |  i j o g  |  i | i d <n |  i | i i |  | i o |  i | i d i |  q. q. Wd S(   sG  
        Create a new context-free grammar, from the given start state
        and set of C{Production}s.
        
        @param start: The start symbol
        @type start: L{Nonterminal}
        @param productions: The list of productions that defines the grammar
        @type productions: C{list} of L{Production}
        i    N(   t   _startt   _productionst
   _lhs_indext
   _rhs_indexR,   R.   t   append(   R   t   startt   productionst   prod(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   w  s    
				
 !
c         C   s   |  i  S(   N(   R5   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR:     s    c         C   s¹   | o | o |  i  Sn | o | o |  i i | g   Snu | o | o |  i i | g   SnO g  } |  i i | g   D]- } | |  i i | g   j o | | q q ~ Sd  S(   N(   R6   R7   t   getR8   (   R   R/   R   R%   R<   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR;     s     c         C   s|   g  } | D]0 } t  |  i d |   d j o | | q q ~ } | o- d i d   | D  } t d |   n d S(   sz   
        Check whether the grammar rules cover the given list of tokens.
        If not, then raise an exception.
        R   i    s   , c         s   s    x |  ] } d  | f Vq Wd S(   s   %rN(    (   t   .0t   w(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pys	   <genexpr>­  s    s3   Grammar does not cover some of the input words: %r.N(   t   lenR;   t   joint
   ValueError(   R   t   tokensR%   t   tokt   missing(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   check_coverage„  s    3c         C   s<   x5 | D]- } t  |  i d |   d j o t Sq q Wt S(   sÕ   
        Check whether the grammar rules cover the given list of tokens.

        @param tokens: the given list of tokens.
        @type tokens: a C{list} of C{string} objects.
        @return: True/False
        R   i    (   R@   R;   R   t   True(   R   RC   t   token(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   covers³  s
     c         C   s   d t  |  i  S(   Ns   <Grammar with %d productions>(   R@   R6   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   Ą  s    c         C   sJ   d t  |  i  } | d |  i 7} x |  i D] } | d | 7} q. W| S(   Ns   Grammar with %d productionss    (start state = %s)s   
    %s(   R@   R6   R5   (   R   R)   t
   production(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   Ć  s    
 (   R   R   R   R   R:   t   NoneR;   RF   RI   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR4   n  s   					t   Grammarc           B   s   e  Z e d   d    Z RS(   s$   Use nltk.ContextFreeGrammar instead.c         O   s   t  i |  | |  d  S(   N(   R4   R   (   R   t   argst   kwargs(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   Ė  s    (   R   R   R    R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRL   Ź  s   t   DependencyGrammarc           B   s;   e  Z d  Z d   Z d   Z d   Z d   Z d   Z RS(   sÆ   
    A dependency grammar.  A DependencyGrammar consists of a set of
    productions.  Each production specifies a head/modifier relationship
    between a pair of words.
    c         C   s   | |  _  d S(   sÜ   
        Create a new dependency grammar, from the set of C{Production}s.
        
        @param productions: The list of productions that defines the grammar
        @type productions: C{list} of L{Production}
        N(   R6   (   R   R;   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   Ö  s    c         C   sQ   xJ |  i  D]? } x6 | i D]+ } | i | j o | | j o t Sq q Wq
 Wt S(   sB  
        @param head: A head word.
        @type head: C{string}.
        @param mod: A mod word, to test as a modifier of 'head'.
        @type mod: C{string}.

        @return: true if this C{DependencyGrammar} contains a 
            C{DependencyProduction} mapping 'head' to 'mod'.
        @rtype: C{boolean}.
        (   R6   R.   R,   RG   R   (   R   t   headt   modRJ   t   possibleMod(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   containsß  s    
 
 c         C   sQ   xJ |  i  D]? } x6 | i D]+ } | i | j o | | j o t Sq q Wq
 Wt S(   sB  
        @param head: A head word.
        @type head: C{string}.
        @param mod: A mod word, to test as a modifier of 'head'.
        @type mod: C{string}.

        @return: true if this C{DependencyGrammar} contains a 
            C{DependencyProduction} mapping 'head' to 'mod'.
        @rtype: C{boolean}.
        (   R6   R.   R,   RG   R   (   R   RP   RQ   RJ   RR   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   __contains__š  s    
 
 c         C   s9   d t  |  i  } x |  i D] } | d | 7} q W| S(   s|   
        @return: A verbose string representation of the
            C{DependencyGrammar}
        @rtype: C{string}
        s&   Dependency grammar with %d productionss   
  %s(   R@   R6   (   R   R)   RJ   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s
    
 c         C   s   d t  |  i  S(   sb   
        @return: A concise string representation of the
            C{DependencyGrammar}
        s&   Dependency grammar with %d productions(   R@   R6   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s    (   R   R   R   R   RS   RT   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRO   Š  s   					t   StatisticalDependencyGrammarc           B   s2   e  Z d  Z d   Z d   Z d   Z d   Z RS(   s   

    c         C   s   | |  _  | |  _ | |  _ d  S(   N(   R6   t   _eventst   _tags(   R   R;   t   eventst   tags(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   %  s    		c         C   sQ   xJ |  i  D]? } x6 | i D]+ } | i | j o | | j o t Sq q Wq
 Wt S(   sB  
        @param head: A head word.
        @type head: C{string}.
        @param mod: A mod word, to test as a modifier of 'head'.
        @type mod: C{string}.

        @return: true if this C{DependencyGrammar} contains a 
            C{DependencyProduction} mapping 'head' to 'mod'.
        @rtype: C{boolean}.
        (   R6   R.   R,   RG   R   (   R   RP   RQ   RJ   RR   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRS   *  s    
 
 c      
   C   s«   d t  |  i  } x |  i D] } | d | 7} q W| d 7} x, |  i D]! } | d |  i | | f 7} qI W| d 7} x, |  i D]! } | d | |  i | f 7} q W| S(   s   
        @return: A verbose string representation of the
            C{StatisticalDependencyGrammar}
        @rtype: C{string}
        s2   Statistical dependency grammar with %d productionss   
  %ss   
Events:s   
  %d:%ss   
Tags:s
   
 %s:	(%s)(   R@   R6   RV   RW   (   R   R)   RJ   t   eventt   tag_word(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   ;  s    
 

 

 c         C   s   d t  |  i  S(   sm   
        @return: A concise string representation of the
            C{StatisticalDependencyGrammar}
        s2   Statistical Dependency grammar with %d productions(   R@   R6   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   L  s    (   R   R   R   R   RS   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRU      s
   			t   WeightedGrammarc           B   s   e  Z d  Z d Z d   Z RS(   sŃ  
    A probabilistic context-free grammar.  A Weighted Grammar consists
    of a start state and a set of weighted productions.  The set of
    terminals and nonterminals is implicitly specified by the
    productions.

    PCFG productions should be C{WeightedProduction}s.
    C{WeightedGrammar}s impose the constraint that the set of
    productions with any given left-hand-side must have probabilities
    that sum to 1.

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

    @type EPSILON: C{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{®Gįz?c         C   s·   t  i |  | |  h  } x: | D]2 } | i | i   d  | i   | | i   <q  WxZ | i   D]L \ } } d t i | j  o d t i j  n p t d |   qc qc Wd S(   sļ  
        Create a new context-free grammar, from the given start state
        and set of C{WeightedProduction}s.

        @param start: The start symbol
        @type start: L{Nonterminal}
        @param productions: The list of productions that defines the grammar
        @type productions: C{list} of C{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.
        i    i   s"   Productions for %r do not sum to 1N(	   R4   R   R=   R/   R3   t   itemsR\   t   EPSILONRB   (   R   R:   R;   t   probsRJ   R/   t   p(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   j  s      (   R   R   R   R^   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR\   T  s   c         C   s¾   h  } h  } xN | D]F } | i  | i   d  d | | i   <| i  | d  d | | <q Wg  } | D]@ } | t | i   | i   d t | |  | | i   qh ~ } t |  |  S(   sČ  
    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: L{Nonterminal}
    @param productions: The list of productions that defines the grammar
    @type productions: C{list} of L{Production}
    i    i   R3   (   R=   R/   R2   R   t   floatR\   (   R:   R;   t   pcountt   lcountR<   R%   R`   t   prods(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   induce_pcfg  s     &Mc         C   s   t  |  t  S(   s'   
    Returns a list of productions
    (   t   parse_productiont   standard_nonterm_parser(   R&   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   parse_cfg_production«  s    c         C   s"   t  |  t  \ } } t | |  S(   N(   t   parse_grammarRg   R4   (   R&   R:   R;   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt	   parse_cfg±  s    c         C   s   t  |  t d t S(   s,   
    Returns a list of PCFG productions
    t   probabilistic(   Rf   Rg   RG   (   R&   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   parse_pcfg_production·  s    c         C   s(   t  |  t d t \ } } t | |  S(   NRk   (   Ri   Rg   RG   R\   (   R&   R:   R;   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt
   parse_pcfg½  s    c         C   s¾  d } | |  |  \ } } t  i d  i |  |  } | p t d   n | i   } d g } t } } g  g }	 xŅ| t |   j  o¾t  i d  i |  |  } | oc | o\ | i   } t | i d  d d ! | d <| d d j o t d	 | d f   q'n|  | d
 j o t  i d  i |  |  } | p t d   n | o t d   n t	 } |	 d i
 | i d  d d ! | i   } n |  | d j oI | i
 d  t } } |	 i
 g   t  i d  i |  |  i   } n- | |  |  \ }
 } |	 d i
 |
  t	 } | o | o t d   qx qx W| oA g  } t |	 |  D]" \ } } | t | | d | qe~ Sn) g  } |	 D] } | t | |  q~ Sd  S(   Ni    s   \s*->\s*s   Expected an arrowg        s   (\[[\d\.]+\])\s*i   i’’’’g      š?s9   Production probability %f, should not be greater than 1.0s   '"s	   ("[^"]+"|s   '[^']+')\s*s   Unterminated strings7   Bad right-hand-side: do not use a sequence of terminalst   |s   \|\s*s;   Bad right-hand-side: do not mix terminals and non-terminalsR3   s   ("[^"]+"|'[^']+')\s*(   t   ret   compilet   matchRB   t   endR   R@   Ra   t   groupRG   R9   t   zipR2   R(   (   t   linet   nonterm_parserRk   t   posR/   t   mt   probabilitiest   found_terminalt   found_non_terminalt   rhsidest   nontermR%   R   t   probabilityt   _[2](    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRf   Ä  sL    	
	 !
%:c      	   C   sĖ  t  |  t  o |  i d  } n |  } t } g  } d } xTt |  D]F\ } } | | i   } | i d  p | d j o qH n | i d  o | d  i   d } qH n d } y  | d d j ou | d	 i t d	  \ }	 }
 |	 d
 j o< | |
 d  \ } } | t	 |
  j o t
 d   q>qXt
 d   n | t | | |  7} WqH t
 j
 o& } t
 d | d	 | | f   qH XqH W| p t
 d  n | p | d i   } n | | f S(   sS  
    Return a starting category and a list of C{Production}s.
    
    @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 C{(string,position)} as argument and return
    a C{(nonterminal,position)} as result. 
    s   
t    t   #s   \i’’’’t    i    t   %i   R:   s   Bad argument to start directives   Bad directives   Unable to parse line %s: %s
%ss   No productions found!(   R   R)   R!   RK   t	   enumerateR"   t
   startswitht   endswitht   rstripR@   RB   Rf   R/   (   t   inputRv   Rk   t   linesR:   R;   t   continue_linet   linenumRu   t	   directiveRM   Rw   t   e(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRi     s>    
 $ c         C   sY   t  i d  i |  |  } | p t d |  |   n t | i d   | i   f S(   Ns   ([\w/]+)\s*s   Expected a nonterminal, found: i   (   Ro   Rp   Rq   RB   R   Rs   Rr   (   t   stringRw   Rx   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyRg   0  s    s   Use nltk.parse_fcfg() instead.c         C   s
   t  |   S(   N(   t
   parse_fcfg(   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   parse_featcfg6  s    t   FeatStructNonterminalc           B   s    e  Z d  Z d   Z d   Z RS(   s|   A feature structure that's also a nonterminal.  It acts as its
    own symbol, and automatically freezes itself when hashed.c         C   s   |  i    t i |   S(   N(   t   freezeR   R   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   @  s    
c         C   s   |  S(   N(    (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   C  s    (   R   R   R   R   R   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   =  s   	c         C   s   t  |  |  S(   N(   Rf   (   R   t   fstruct_parser(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   parse_fcfg_productionF  s    c         C   s   | t  j o t t f } n | t  j o t | t d | } n | t  j	 o t d   n t |  | i  \ } } t | |  S(   s»  
    Return a feature structure 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 
                         (default: LogicParser())
    @param fstruct_parser: a feature structure parser 
                           (only if features and logic_parser is None)
    t   logic_parsers8   'logic_parser' and 'fstruct_parser' must not both be set(	   RK   R   R   R   R   t	   ExceptionRi   t   partial_parseR4   (   R   t   featuresR   R   R:   R;   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR   I  s    sH  ^\s*                # leading whitespace
                              ('[^']+')\s*        # single-quoted lhs
                              (?:[-=]+>)\s*        # arrow
                              (?:(                 # rhs:
                                   "[^"]+"         # doubled-quoted terminal
                                 | '[^']+'         # single-quoted terminal
                                 | \|              # disjunction
                                 )
                                 \s*)              # trailing space
                                 *$s"   ('[^']'|[-=]+>|"[^"]+"|'[^']+'|\|)c         C   sĆ   g  } x t  |  i d   D]y \ } } | i   } | i d  p | d j o q n y | t |  7} Wq t j
 o t d | | f  q Xq Wt |  d j o t d  n t |  S(   Ns   
R   R   s   Unable to parse line %s: %si    s   No productions found!(   R   R!   R"   R   t   parse_dependency_productionRB   R@   RO   (   R&   R;   R   Ru   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   parse_dependency_grammart  s     $c   
      C   s’   t  i |   p t d  n t i |   } g  } t |  D]( \ } } | d d j o | | q= q= ~ } | d i d  } g  g } xJ | d D]> } | d j o | i g   q | d i | i d   q Wg  } | D] }	 | t | |	  qā ~ S(   Ns   Bad production stringi   i   i    s   '"Rn   i’’’’(	   t   _PARSE_DG_RERq   RB   t   _SPLIT_DG_RER!   R   R"   R9   R1   (
   R&   t   piecesR%   t   iR`   t   lhsideR|   t   pieceR   t   rhside(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyR     s    B	 c          C   s  d d k  l }  l } l } |  d  \ } } } } |  d  \ } } }	 }
 | | } d G| | | | | | |	 |
 | | g	 GHd G| i   GHH| | | g  GH| d  } d G| GHd	 G| i   GHd
 G| i   i d d d d  GHHd GH| i d d g  GH| i d d g  GHd S(   sU   
    A demonstration showing how C{ContextFreeGrammar}s can be created and used.
    i’’’’(   R'   R(   Rj   s   S, NP, VP, PPs   N, V, P, Dets   Some nonterminals:s       S.symbol() =>sæ   
      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'
    s
   A Grammar:s       grammar.start()       =>s       grammar.productions() =>R    s   ,
R   i   s%   Coverage of input words by a grammar:t   at   dogt   toyN(	   t   nltkR'   R(   Rj   R   R:   R;   t   replaceRI   (   R'   R(   Rj   t   St   NPt   VPt   PPt   Nt   Vt   Pt   Dett   VP_slash_NPt   grammar(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   cfg_demo  s$    
(		
 s7  
    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]
    sä  
    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]
    c       
   C   só  d d k  l }  d d k l } d d k l } d d k l } t i   } | d } d G| GHd G| i	   GHd	 G| i
   GHd
 G| i   GHHt } d G| GHd G| i   GHd G| i   i d d d d  GHHd GH| i d d g  GH| i d d g  GHd GHg  } x_ |  i d  D]P } xG |  i |  D]6 }	 |	 i d t  |	 i d d  | |	 i   7} q2WqWt d  }
 | |
 |  } | GHHd GH| i |  } | i d  |  i d  d i   } | GHx | i |  D] } | GHqąWd S(   sR   
    A demonstration showing how C{WeightedGrammar}s can be created and used.
    i’’’’(   t   treebank(   t   treetransforms(   Re   (   t   pcharti   s   A PCFG production:s       pcfg_prod.lhs()  =>s       pcfg_prod.rhs()  =>s       pcfg_prod.prob() =>s   A PCFG grammar:s       grammar.start()       =>s       grammar.productions() =>R    s   ,
R   i   s%   Coverage of input words by a grammar:R¢   t   boyt   girls'   Induce PCFG grammar from treebank data:t   collapsePOSt
   horzMarkovR§   s%   Parse sentence using induced grammar:i   s   wsj_0001.mrgi    N(   t   nltk.corpusR²   R„   R³   Re   t
   nltk.parseR“   t	   toy_pcfg1R;   R/   R   R3   t	   toy_pcfg2R:   R¦   RI   R]   t   parsed_sentst   collapse_unaryR   t   chomsky_normal_formR   t   InsideChartParsert   tracet   leavest   nbest_parse(   R²   R³   Re   R“   t
   pcfg_prodst	   pcfg_prodR°   R;   t   itemt   treeR§   t   parsert   sentt   parse(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt	   pcfg_demoą  sR    


    c          C   s(   d d  k  }  |  i i d  } | GHHd  S(   Ni’’’’s!   grammars/book_grammars/feat0.fcfg(   t	   nltk.datat   datat   load(   R„   t   g(    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt	   fcfg_demo  s    c          C   s   t  d  }  |  GHd S(   s]   
    A demonstration showing the creation and inspection of a 
    C{DependencyGrammar}.
    sP   
    'scratch' -> 'cats' | 'walls'
    'walls' -> 'the'
    'cats' -> 'the'
    N(   R   (   R°   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   dg_demo#  s    	c          C   s'   t  d  }  |  i   } | i   GHd S(   sh   
    A demonstration of how to read a string representation of 
    a CoNLL format dependency tree.
    sg  
    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(   t   DependencyGraphRĒ   t   pprint(   t   dgRĒ   (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   sdg_demo/  s    	c           C   s'   t    t   t   t   t   d  S(   N(   R±   RĖ   RŠ   RŃ   RÕ   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pyt   demoF  s
    t   __main__R'   Re   Rj   Rh   Rm   Rl   R   R   Ri   Rf   R   R   RÖ   R±   RĖ   RŃ   RÕ   R»   R¼   (5   R   Ro   t   nltk.internalsR    R~   R   t
   featstructR   R   R   R   R   t   objectR   R'   R(   R1   R2   R4   RL   RO   RU   R\   Re   Rh   Rj   Rl   Rm   R   Rf   Ri   Rg   R   R   R   RK   R   Rp   t   VERBOSER   R   R   R   R±   R»   R¼   RĖ   RŠ   RŃ   RÕ   RÖ   R   t   __all__(    (    (    s"   /p/zhu/06/nlp/nltk/nltk/grammar.pys   <module>F   sn   (g	`-\P41	&				=/							)				=							