
    g                        d dl Z d dlZd dlmZ d dlmZ  G d d      Z G d d      Z G d d	e      Z G d
 de      Z	 G d de      Z
 G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z e j                   dj#                  dd            Zd Z G d de      Z G d de      Zd  Zd! Zed"k(  r e        yy)#    N)ChunkParserITreec                       e Zd ZdZdZdez  ZdZdZdez  Zdez  Z	 e
j                  dez        Z e
j                  d	      Z e
j                  d
      ZddZd Zd ZddZd Zd Zd Zy)ChunkStringaL  
    A string-based encoding of a particular chunking of a text.
    Internally, the ``ChunkString`` class uses a single string to
    encode the chunking of the input text.  This string contains a
    sequence of angle-bracket delimited tags, with chunking indicated
    by braces.  An example of this encoding is::

        {<DT><JJ><NN>}<VBN><IN>{<DT><NN>}<.>{<DT><NN>}<VBD><.>

    ``ChunkString`` are created from tagged texts (i.e., lists of
    ``tokens`` whose type is ``TaggedType``).  Initially, nothing is
    chunked.

    The chunking of a ``ChunkString`` can be modified with the ``xform()``
    method, which uses a regular expression to transform the string
    representation.  These transformations should only add and remove
    braces; they should *not* modify the sequence of angle-bracket
    delimited tags.

    :type _str: str
    :ivar _str: The internal string representation of the text's
        encoding.  This string representation contains a sequence of
        angle-bracket delimited tags, with chunking indicated by
        braces.  An example of this encoding is::

            {<DT><JJ><NN>}<VBN><IN>{<DT><NN>}<.>{<DT><NN>}<VBD><.>

    :type _pieces: list(tagged tokens and chunks)
    :ivar _pieces: The tagged tokens and chunks encoded by this ``ChunkString``.
    :ivar _debug: The debug level.  See the constructor docs.

    :cvar IN_CHUNK_PATTERN: A zero-width regexp pattern string that
        will only match positions that are in chunks.
    :cvar IN_STRIP_PATTERN: A zero-width regexp pattern string that
        will only match positions that are in strips.
    z	[^\{\}<>]z(<%s+?>)z(?=[^\{]*\})z(?=[^\}]*(\{|$))z(\{%s+?\})+?z(%s+?)+?z^(\{?%s\}?)*?$z[^\{\}]+z(\{\})*$c                     |j                         | _        |dd | _        | j                  D cg c]  }| j                  |       }}ddj	                  |      z   dz   | _        || _        yc c}w )a}  
        Construct a new ``ChunkString`` that encodes the chunking of
        the text ``tagged_tokens``.

        :type chunk_struct: Tree
        :param chunk_struct: The chunk structure to be further chunked.
        :type debug_level: int
        :param debug_level: The level of debugging which should be
            applied to transformations on the ``ChunkString``.  The
            valid levels are:

                - 0: no checks
                - 1: full check on to_chunkstruct
                - 2: full check on to_chunkstruct and cursory check after
                  each transformation.
                - 3: full check on to_chunkstruct and full check after
                  each transformation.

            We recommend you use at least level 1.  You should
            probably use level 3 if you use any non-standard
            subclasses of ``RegexpChunkRule``.
        N<z><>)label_root_label_pieces_tagjoin_str_debug)selfchunk_structdebug_leveltoktagss        F/var/www/openai/venv/lib/python3.12/site-packages/nltk/chunk/regexp.py__init__zChunkString.__init__H   se    . (--/#A*.,,7,3		#,7$))D/)C/	! 8s   A,c                     t        |t              r|d   S t        |t              r|j                         S t	        d      )N   z4chunk structures must contain tagged tokens or trees)
isinstancetupler   r   
ValueError)r   r   s     r   r   zChunkString._tage   s7    c5!q6MT"99;VWW    c                 
   t         j                  j                  |      st        d|z        t         j                  j                  d|      }t        dt        |      dz  z         D ]=  }||dz  |dz  dz    }t         j                  j                  |      r1t        d|z         |dk  ryt        j                  d|      dd }| j                  D cg c]  }| j                  |       }}||k7  rt        d	      yc c}w )
a  
        Check to make sure that ``s`` still corresponds to some chunked
        version of ``_pieces``.

        :type verify_tags: bool
        :param verify_tags: Whether the individual tags should be
            checked.  If this is false, ``_verify`` will check to make
            sure that ``_str`` encodes a chunked version of *some*
            list of tokens.  If this is true, then ``_verify`` will
            check to make sure that the tags in ``_str`` match those in
            ``_pieces``.

        :raise ValueError: if the internal string representation of
            this ``ChunkString`` is invalid or not consistent with _pieces.
        z2Transformation generated invalid chunkstring:
  %s r   i  r   Nz	[\{\}<>]+z9Transformation generated invalid chunkstring: tag changed)r   _VALIDmatchr   	_BRACKETSsubrangelen_BALANCED_BRACKETSresplitr   r   )	r   sverify_tagsbracketsisubstrtags1piecetags2s	            r   _verifyzChunkString._verifym   s   " !!''*H1L  ((,,R3q3x=D001Aa$hTD9F1177? LqP  2 !,*Ab1/3||<|e5!|<E>N   =s   D c                 v   | j                   dkD  r| j                  | j                  d       g }d}d}t        j                  d| j                        D ]P  }|j                  d      }| j                  |||z    }|r|j                  t        ||             n||z  }||z  }| }R t        | j                  |      S )z
        Return the chunk structure encoded by this ``ChunkString``.

        :rtype: Tree
        :raise ValueError: If a transformation has generated an
            invalid chunkstring.
        r   r   [{}]r	   )
r   r3   r   r)   r*   countr   appendr   r   )r   chunk_labelpiecesindexpiece_in_chunkr1   lengthsubsequences           r   to_chunkstructzChunkString.to_chunkstruct   s     ;;?LLA& XXfdii0E[[%F,,uuv~>K d;<=+% VOE!//N 1 D$$f--r   c                     t        j                  ||| j                        }t        j                  dd|      }| j                  dkD  r| j	                  || j                  dz
         || _        y)aH  
        Apply the given transformation to the string encoding of this
        ``ChunkString``.  In particular, find all occurrences that match
        ``regexp``, and replace them using ``repl`` (as done by
        ``re.sub``).

        This transformation should only add and remove braces; it
        should *not* modify the sequence of angle-bracket delimited
        tags.  Furthermore, this transformation may not result in
        improper bracketing.  Note, in particular, that bracketing may
        not be nested.

        :type regexp: str or regexp
        :param regexp: A regular expression matching the substring
            that should be replaced.  This will typically include a
            named group, which can be used by ``repl``.
        :type repl: str
        :param repl: An expression specifying what should replace the
            matched substring.  Typically, this will include a named
            replacement group, specified by ``regexp``.
        :rtype: None
        :raise ValueError: If this transformation generated an
            invalid chunkstring.
        z\{\}r    r      N)r)   r%   r   r   r3   )r   regexpreplr+   s       r   xformzChunkString.xform   sZ    4 FF64+
 FF7B" ;;?LLDKK!O, 	r   c                 2    dt        | j                        z  S )z
        Return a string representation of this ``ChunkString``.
        It has the form::

            <ChunkString: '{<DT><JJ><NN>}<VBN><IN>{<DT><NN>}'>

        :rtype: str
        z<ChunkString: %s>)reprr   r   s    r   __repr__zChunkString.__repr__   s     #T$))_44r   c                     t        j                  dd| j                        }t        j                  dd|      }|d   dk(  rd|z   }|S )a)  
        Return a formatted representation of this ``ChunkString``.
        This representation will include extra spaces to ensure that
        tags will line up with the representation of other
        ``ChunkStrings`` for the same text, regardless of the chunking.

        :rtype: str
        z>(?!\})z> z([^\{])<z\1 <r   r	    )r)   r%   r   )r   strs     r   __str__zChunkString.__str__   sE     ffZ		2ff['3/q6S=)C
r   N)r   )CHUNK)__name__
__module____qualname____doc__CHUNK_TAG_CHAR	CHUNK_TAGIN_CHUNK_PATTERNIN_STRIP_PATTERN_CHUNK_STRIPr)   compiler"   r$   r(   r   r   r3   r>   rC   rG   rK    r   r   r   r      s    #J "Nn,I&* y(F9$FRZZ)I56F

;'I#K0":X)V.@&P	5r   r   c                   8    e Zd ZdZd Zd Zd Zd Zed        Z	y)RegexpChunkRulea  
    A rule specifying how to modify the chunking in a ``ChunkString``,
    using a transformational regular expression.  The
    ``RegexpChunkRule`` class itself can be used to implement any
    transformational rule based on regular expressions.  There are
    also a number of subclasses, which can be used to implement
    simpler types of rules, based on matching regular expressions.

    Each ``RegexpChunkRule`` has a regular expression and a
    replacement expression.  When a ``RegexpChunkRule`` is "applied"
    to a ``ChunkString``, it searches the ``ChunkString`` for any
    substring that matches the regular expression, and replaces it
    using the replacement expression.  This search/replace operation
    has the same semantics as ``re.sub``.

    Each ``RegexpChunkRule`` also has a description string, which
    gives a short (typically less than 75 characters) description of
    the purpose of the rule.

    This transformation defined by this ``RegexpChunkRule`` should
    only add and remove braces; it should *not* modify the sequence
    of angle-bracket delimited tags.  Furthermore, this transformation
    may not result in nested or mismatched bracketing.
    c                 x    t        |t              rt        j                  |      }|| _        || _        || _        y)a  
        Construct a new RegexpChunkRule.

        :type regexp: regexp or str
        :param regexp: The regular expression for this ``RegexpChunkRule``.
            When this rule is applied to a ``ChunkString``, any
            substring that matches ``regexp`` will be replaced using
            the replacement string ``repl``.  Note that this must be a
            normal regular expression, not a tag pattern.
        :type repl: str
        :param repl: The replacement expression for this ``RegexpChunkRule``.
            When this rule is applied to a ``ChunkString``, any substring
            that matches ``regexp`` will be replaced using ``repl``.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        N)r   rJ   r)   rW   _repl_descr_regexp)r   rA   rB   descrs       r   r   zRegexpChunkRule.__init__  s1    $ fc"ZZ'F
r   c                 P    |j                  | j                  | j                         y)a  
        Apply this rule to the given ``ChunkString``.  See the
        class reference documentation for a description of what it
        means to apply a rule.

        :type chunkstr: ChunkString
        :param chunkstr: The chunkstring to which this rule is applied.
        :rtype: None
        :raise ValueError: If this transformation generated an
            invalid chunkstring.
        N)rC   r^   r\   )r   chunkstrs     r   applyzRegexpChunkRule.apply3  s     	t||TZZ0r   c                     | j                   S )zt
        Return a short description of the purpose and/or effect of
        this rule.

        :rtype: str
        )r]   rF   s    r   r_   zRegexpChunkRule.descrB  s     {{r   c                 ~    dt        | j                  j                        z   dz   t        | j                        z   dz   S )a@  
        Return a string representation of this rule.  It has the form::

            <RegexpChunkRule: '{<IN|VB.*>}'->'<IN>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<RegexpChunkRule: z->r
   )rE   r^   patternr\   rF   s    r   rG   zRegexpChunkRule.__repr__K  sH     !4<<''() 4:: 		
r   c                    t        j                  d|       }|j                  d      j                         }|j                  d      xs ddd j                         }	 |st	        d      |d   d	k(  r|d
   dk(  rt        |dd
 |      S |d   dk(  r|d
   d	k(  rt        |dd
 |      S d|v r!|j                  d      \  }}t        |||      S d|v r!|j                  d      \  }}t        |||      S t        j                  d|      r(t        j                  d|      \  }}}t        ||||      S t	        d|z        # t        t         j                  f$ r}t	        d|z        |d}~ww xY w)a^  
        Create a RegexpChunkRule from a string description.
        Currently, the following formats are supported::

          {regexp}         # chunk rule
          }regexp{         # strip rule
          regexp}{regexp   # split rule
          regexp{}regexp   # merge rule

        Where ``regexp`` is a regular expression for the rule.  Any
        text following the comment marker (``#``) will be used as
        the rule's description:

        >>> from nltk.chunk.regexp import RegexpChunkRule
        >>> RegexpChunkRule.fromstring('{<DT>?<NN.*>+}')
        <ChunkRule: '<DT>?<NN.*>+'>
        z&(?P<rule>(\\.|[^#])*)(?P<comment>#.*)?rulecommentr    r   NzEmpty chunk patternr   {r!   }z}{z{}z[^{}]*{[^{}]*}[^{}]*r5   zIllegal chunk pattern: %s)r)   r#   groupstripr   	ChunkRule	StripRuler*   	SplitRule	MergeRuleChunkRuleWithContexterror)r+   mrg   rh   leftrightchunkes           r   
fromstringzRegexpChunkRule.fromstring_  sy   ( HH>Bwwv$$&779%+QR0668	H !677Aw#~$r(c/ aW55aCDHO aW55"jj.e ug66"jj.e ug660$7%'XXfd%;"eU+D%HH !<t!CDDBHH% 	H84?@aG	Hs6   +D> 	D> ($D> $D> 2=D> 0D> >E+E&&E+N)
rM   rN   rO   rP   r   rb   r_   rG   staticmethodrx   rX   r   r   rZ   rZ     s1    201
( +H +Hr   rZ   c                       e Zd ZdZd Zd Zy)rm   a)  
    A rule specifying how to add chunks to a ``ChunkString``, using a
    matching tag pattern.  When applied to a ``ChunkString``, it will
    find any substring that matches this tag pattern and that is not
    already part of a chunk, and create a new chunk containing that
    substring.
    c                     || _         t        j                  dt        |      dt        j
                        }t        j                  | |d|       y)a  
        Construct a new ``ChunkRule``.

        :type tag_pattern: str
        :param tag_pattern: This rule's tag pattern.  When
            applied to a ``ChunkString``, this rule will
            chunk any substring that matches this tag pattern and that
            is not already part of a chunk.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        z
(?P<chunk>)z{\g<chunk>}N)_patternr)   rW   tag_pattern2re_patternr   rT   rZ   r   r   tag_patternr_   rA   s       r   r   zChunkRule.__init__  sE     $%k2K4P4PR
 	  v~uEr   c                 8    dt        | j                        z   dz   S )a0  
        Return a string representation of this rule.  It has the form::

            <ChunkRule: '<IN|VB.*>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<ChunkRule: r
   rE   r}   rF   s    r   rG   zChunkRule.__repr__       T]] 33c99r   NrM   rN   rO   rP   r   rG   rX   r   r   rm   rm     s    F(:r   rm   c                       e Zd ZdZd Zd Zy)rn   a0  
    A rule specifying how to remove strips to a ``ChunkString``,
    using a matching tag pattern.  When applied to a
    ``ChunkString``, it will find any substring that matches this
    tag pattern and that is contained in a chunk, and remove it
    from that chunk, thus creating two new chunks.
    c                     || _         t        j                  dt        |      dt        j
                        }t        j                  | |d|       y)a  
        Construct a new ``StripRule``.

        :type tag_pattern: str
        :param tag_pattern: This rule's tag pattern.  When
            applied to a ``ChunkString``, this rule will
            find any substring that matches this tag pattern and that
            is contained in a chunk, and remove it from that chunk,
            thus creating two new chunks.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        z
(?P<strip>r|   z}\g<strip>{N)r}   r)   rW   r~   r   rS   rZ   r   r   s       r   r   zStripRule.__init__  sE     $%k2K4P4PR
 	  v~uEr   c                 8    dt        | j                        z   dz   S )a0  
        Return a string representation of this rule.  It has the form::

            <StripRule: '<IN|VB.*>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<StripRule: r
   r   rF   s    r   rG   zStripRule.__repr__  r   r   Nr   rX   r   r   rn   rn     s    F*:r   rn   c                       e Zd ZdZd Zd Zy)UnChunkRulez
    A rule specifying how to remove chunks to a ``ChunkString``,
    using a matching tag pattern.  When applied to a
    ``ChunkString``, it will find any complete chunk that matches this
    tag pattern, and un-chunk it.
    c                     || _         t        j                  dt        |      z        }t        j                  | |d|       y)a  
        Construct a new ``UnChunkRule``.

        :type tag_pattern: str
        :param tag_pattern: This rule's tag pattern.  When
            applied to a ``ChunkString``, this rule will
            find any complete chunk that matches this tag pattern,
            and un-chunk it.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        z\{(?P<chunk>%s)\}z	\g<chunk>N)r}   r)   rW   r~   rZ   r   r   s       r   r   zUnChunkRule.__init__  s9     $03I+3VVW  v|UCr   c                 8    dt        | j                        z   dz   S )a2  
        Return a string representation of this rule.  It has the form::

            <UnChunkRule: '<IN|VB.*>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<UnChunkRule: r
   r   rF   s    r   rG   zUnChunkRule.__repr__   s      $t}}"55;;r   Nr   rX   r   r   r   r     s    D"<r   r   c                       e Zd ZdZd Zd Zy)rp   a~  
    A rule specifying how to merge chunks in a ``ChunkString``, using
    two matching tag patterns: a left pattern, and a right pattern.
    When applied to a ``ChunkString``, it will find any chunk whose end
    matches left pattern, and immediately followed by a chunk whose
    beginning matches right pattern.  It will then merge those two
    chunks into a single chunk.
    c                 $   t        j                  t        |             t        j                  t        |             || _        || _        t        j                  dt        |      dt        |      d      }t
        j                  | |d|       y)a  
        Construct a new ``MergeRule``.

        :type right_tag_pattern: str
        :param right_tag_pattern: This rule's right tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose end matches
            ``left_tag_pattern``, and immediately followed by a chunk
            whose beginning matches this pattern.  It will
            then merge those two chunks into a single chunk.
        :type left_tag_pattern: str
        :param left_tag_pattern: This rule's left tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose end matches
            this pattern, and immediately followed by a chunk
            whose beginning matches ``right_tag_pattern``.  It will
            then merge those two chunks into a single chunk.

        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        	(?P<left>z)}{(?=r|   z\g<left>Nr)   rW   r~   _left_tag_pattern_right_tag_patternrZ   r   r   left_tag_patternright_tag_patternr_   rA   s        r   r   zMergeRule.__init__  sw    2 	

)*:;<


)*;<=!1"3 ''78&'89
 	  v{EBr   c                 j    dt        | j                        z   dz   t        | j                        z   dz   S )a<  
        Return a string representation of this rule.  It has the form::

            <MergeRule: '<NN|DT|JJ>', '<NN|JJ>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<MergeRule: , r
   rE   r   r   rF   s    r   rG   zMergeRule.__repr__@  F     4))*+ 4**+, 		
r   Nr   rX   r   r   rp   rp     s    %CN
r   rp   c                       e Zd ZdZd Zd Zy)ro   aw  
    A rule specifying how to split chunks in a ``ChunkString``, using
    two matching tag patterns: a left pattern, and a right pattern.
    When applied to a ``ChunkString``, it will find any chunk that
    matches the left pattern followed by the right pattern.  It will
    then split the chunk into two new chunks, at the point between the
    two pattern matches.
    c                 $   t        j                  t        |             t        j                  t        |             || _        || _        t        j                  dt        |      dt        |      d      }t
        j                  | |d|       y)a  
        Construct a new ``SplitRule``.

        :type right_tag_pattern: str
        :param right_tag_pattern: This rule's right tag
            pattern.  When applied to a ``ChunkString``, this rule will
            find any chunk containing a substring that matches
            ``left_tag_pattern`` followed by this pattern.  It will
            then split the chunk into two new chunks at the point
            between these two matching patterns.
        :type left_tag_pattern: str
        :param left_tag_pattern: This rule's left tag
            pattern.  When applied to a ``ChunkString``, this rule will
            find any chunk containing a substring that matches this
            pattern followed by ``right_tag_pattern``.  It will then
            split the chunk into two new chunks at the point between
            these two matching patterns.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        r   z)(?=r|   z
\g<left>}{Nr   r   s        r   r   zSplitRule.__init___  sw    0 	

)*:;<


)*;<=!1"3 ''78&'89
 	  v}eDr   c                 j    dt        | j                        z   dz   t        | j                        z   dz   S )a3  
        Return a string representation of this rule.  It has the form::

            <SplitRule: '<NN>', '<DT>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<SplitRule: r   r
   r   rF   s    r   rG   zSplitRule.__repr__  r   r   Nr   rX   r   r   ro   ro   U  s    $EL
r   ro   c                       e Zd ZdZd Zd Zy)ExpandLeftRulea  
    A rule specifying how to expand chunks in a ``ChunkString`` to the left,
    using two matching tag patterns: a left pattern, and a right pattern.
    When applied to a ``ChunkString``, it will find any chunk whose beginning
    matches right pattern, and immediately preceded by a strip whose
    end matches left pattern.  It will then expand the chunk to incorporate
    the new material on the left.
    c                 $   t        j                  t        |             t        j                  t        |             || _        || _        t        j                  dt        |      dt        |      d      }t
        j                  | |d|       y)a  
        Construct a new ``ExpandRightRule``.

        :type right_tag_pattern: str
        :param right_tag_pattern: This rule's right tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose beginning matches
            ``right_tag_pattern``, and immediately preceded by a strip
            whose end matches this pattern.  It will
            then merge those two chunks into a single chunk.
        :type left_tag_pattern: str
        :param left_tag_pattern: This rule's left tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose beginning matches
            this pattern, and immediately preceded by a strip
            whose end matches ``left_tag_pattern``.  It will
            then expand the chunk to incorporate the new material on the left.

        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        r   z)\{(?P<right>r|   z{\g<left>\g<right>Nr   r   s        r   r   zExpandLeftRule.__init__  x    2 	

)*:;<


)*;<=!1"3 ''78&'89
 	  v/DeLr   c                 j    dt        | j                        z   dz   t        | j                        z   dz   S )aA  
        Return a string representation of this rule.  It has the form::

            <ExpandLeftRule: '<NN|DT|JJ>', '<NN|JJ>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<ExpandLeftRule: r   r
   r   rF   s    r   rG   zExpandLeftRule.__repr__  sF      4))*+ 4**+, 		
r   Nr   rX   r   r   r   r         %MN
r   r   c                       e Zd ZdZd Zd Zy)ExpandRightRulea  
    A rule specifying how to expand chunks in a ``ChunkString`` to the
    right, using two matching tag patterns: a left pattern, and a
    right pattern.  When applied to a ``ChunkString``, it will find any
    chunk whose end matches left pattern, and immediately followed by
    a strip whose beginning matches right pattern.  It will then
    expand the chunk to incorporate the new material on the right.
    c                 $   t        j                  t        |             t        j                  t        |             || _        || _        t        j                  dt        |      dt        |      d      }t
        j                  | |d|       y)a  
        Construct a new ``ExpandRightRule``.

        :type right_tag_pattern: str
        :param right_tag_pattern: This rule's right tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose end matches
            ``left_tag_pattern``, and immediately followed by a strip
            whose beginning matches this pattern.  It will
            then merge those two chunks into a single chunk.
        :type left_tag_pattern: str
        :param left_tag_pattern: This rule's left tag
            pattern.  When applied to a ``ChunkString``, this
            rule will find any chunk whose end matches
            this pattern, and immediately followed by a strip
            whose beginning matches ``right_tag_pattern``.  It will
            then expand the chunk to incorporate the new material on the right.

        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        r   z)\}(?P<right>r|   z\g<left>\g<right>}Nr   r   s        r   r   zExpandRightRule.__init__  r   r   c                 j    dt        | j                        z   dz   t        | j                        z   dz   S )aB  
        Return a string representation of this rule.  It has the form::

            <ExpandRightRule: '<NN|DT|JJ>', '<NN|JJ>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z<ExpandRightRule: r   r
   r   rF   s    r   rG   zExpandRightRule.__repr__  sF     !4))*+ 4**+, 		
r   Nr   rX   r   r   r   r     r   r   r   c                       e Zd ZdZd Zd Zy)rq   a  
    A rule specifying how to add chunks to a ``ChunkString``, using
    three matching tag patterns: one for the left context, one for the
    chunk, and one for the right context.  When applied to a
    ``ChunkString``, it will find any substring that matches the chunk
    tag pattern, is surrounded by substrings that match the two
    context patterns, and is not already part of a chunk; and create a
    new chunk containing the substring that matched the chunk tag
    pattern.

    Caveat: Both the left and right context are consumed when this
    rule matches; therefore, if you need to find overlapping matches,
    you will need to apply your rule more than once.
    c           
         t        j                  t        |             t        j                  t        |             t        j                  t        |             || _        || _        || _        t        j                  dt        |      dt        |      dt        |      dt        j                        }d}t        j                  | |||       y)aQ  
        Construct a new ``ChunkRuleWithContext``.

        :type left_context_tag_pattern: str
        :param left_context_tag_pattern: A tag pattern that must match
            the left context of ``chunk_tag_pattern`` for this rule to
            apply.
        :type chunk_tag_pattern: str
        :param chunk_tag_pattern: A tag pattern that must match for this
            rule to apply.  If the rule does apply, then this pattern
            also identifies the substring that will be made into a chunk.
        :type right_context_tag_pattern: str
        :param right_context_tag_pattern: A tag pattern that must match
            the right context of ``chunk_tag_pattern`` for this rule to
            apply.
        :type descr: str
        :param descr: A short description of the purpose and/or effect
            of this rule.
        r   z)(?P<chunk>z)(?P<right>r|   z\g<left>{\g<chunk>}\g<right>N)
r)   rW   r~   _left_context_tag_pattern_chunk_tag_pattern_right_context_tag_patternr   rT   rZ   r   )r   left_context_tag_patternchunk_tag_patternright_context_tag_patternr_   rA   replacements          r   r   zChunkRuleWithContext.__init__6  s    8 	

)*BCD


)*;<=


)*CDE)A&"3*C' ''?@&'89&'@A,,
 6  v{EBr   c                 d    dj                  | j                  | j                  | j                        S )aF  
        Return a string representation of this rule.  It has the form::

            <ChunkRuleWithContext: '<IN>', '<NN>', '<DT>'>

        Note that this representation does not include the
        description string; that string can be accessed
        separately with the ``descr()`` method.

        :rtype: str
        z)<ChunkRuleWithContext:  {!r}, {!r}, {!r}>)formatr   r   r   rF   s    r   rG   zChunkRuleWithContext.__repr__e  s2     ;AA**##++
 	
r   Nr   rX   r   r   rq   rq   &  s    -C^
r   rq   z^(({}|<{}>)*)$z"([^\{\}<>]|\{\d+,?\}|\{\d*,\d+\})+z
[^\{\}<>]+c                 V   t        j                  dd|       } t        j                  dd|       } t        j                  dd|       } t        j                  |       st	        d| z        d } |t
        j                        } ||       }t        j                  d	||      } ||      } | S )
a  
    Convert a tag pattern to a regular expression pattern.  A "tag
    pattern" is a modified version of a regular expression, designed
    for matching sequences of tags.  The differences between regular
    expression patterns and tag patterns are:

        - In tag patterns, ``'<'`` and ``'>'`` act as parentheses; so
          ``'<NN>+'`` matches one or more repetitions of ``'<NN>'``, not
          ``'<NN'`` followed by one or more repetitions of ``'>'``.
        - Whitespace in tag patterns is ignored.  So
          ``'<DT> | <NN>'`` is equivalent to ``'<DT>|<NN>'``
        - In tag patterns, ``'.'`` is equivalent to ``'[^{}<>]'``; so
          ``'<NN.*>'`` matches any single tag starting with ``'NN'``.

    In particular, ``tag_pattern2re_pattern`` performs the following
    transformations on the given pattern:

        - Replace '.' with '[^<>{}]'
        - Remove any whitespace
        - Add extra parens around '<' and '>', to make '<' and '>' act
          like parentheses.  E.g., so that in '<NN>+', the '+' has scope
          over the entire '<NN>'; and so that in '<NN|IN>', the '|' has
          scope over 'NN' and 'IN', but not '<' or '>'.
        - Check to make sure the resulting pattern is valid.

    :type tag_pattern: str
    :param tag_pattern: The tag pattern to convert to a regular
        expression pattern.
    :raise ValueError: If ``tag_pattern`` is not a valid tag pattern.
        In particular, ``tag_pattern`` should not include braces; and it
        should not contain nested or mismatched angle-brackets.
    :rtype: str
    :return: A regular expression pattern corresponding to
        ``tag_pattern``.
    z\sr    r	   z(<(r
   z)>)zBad tag pattern: %rc                 Z    t        |       }|j                          dj                  |      S )Nr    )listreverser   )rJ   lsts     r   reverse_strz+tag_pattern2re_pattern.<locals>.reverse_str  s"    3iwws|r   z\.(?!\\(\\\\)*($|[^\\])))r)   r%   CHUNK_TAG_PATTERNr#   r   r   rQ   )r   r   tc_revreverseds       r   r~   r~     s    J &&K0K&&uk2K&&uk2K "";/.<==
 334F;'Hvv168DHh'Kr   c                   >    e Zd ZdZd
dZd Zd ZddZd Zd Z	d	 Z
y)RegexpChunkParseran  
    A regular expression based chunk parser.  ``RegexpChunkParser`` uses a
    sequence of "rules" to find chunks of a single type within a
    text.  The chunking of the text is encoded using a ``ChunkString``,
    and each rule acts by modifying the chunking in the
    ``ChunkString``.  The rules are all implemented using regular
    expression matching and substitution.

    The ``RegexpChunkRule`` class and its subclasses (``ChunkRule``,
    ``StripRule``, ``UnChunkRule``, ``MergeRule``, and ``SplitRule``)
    define the rules that are used by ``RegexpChunkParser``.  Each rule
    defines an ``apply()`` method, which modifies the chunking encoded
    by a given ``ChunkString``.

    :type _rules: list(RegexpChunkRule)
    :ivar _rules: The list of rules that should be applied to a text.
    :type _trace: int
    :ivar _trace: The default level of tracing.

    c                 <    || _         || _        || _        || _        y)a  
        Construct a new ``RegexpChunkParser``.

        :type rules: list(RegexpChunkRule)
        :param rules: The sequence of rules that should be used to
            generate the chunking for a tagged text.
        :type chunk_label: str
        :param chunk_label: The node value that should be used for
            chunk subtrees.  This is typically a short string
            describing the type of information contained by the chunk,
            such as ``"NP"`` for base noun phrases.
        :type root_label: str
        :param root_label: The node value that should be used for the
            top node of the chunk structure.
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.
        N)_rules_trace_chunk_labelr   )r   rulesr8   
root_labeltraces        r   r   zRegexpChunkParser.__init__  s"    * '%r   c                 "   t        d       t        |       | j                  D ]j  }|j                  |       |r-t        d|j                         dz   t	        |      z   dz          nt        d|j                         dz          t        |       l y)a  
        Apply each rule of this ``RegexpChunkParser`` to ``chunkstr``, in
        turn.  Generate trace output between each rule.  If ``verbose``
        is true, then generate verbose output.

        :type chunkstr: ChunkString
        :param chunkstr: The chunk string to which each rule should be
            applied.
        :type verbose: bool
        :param verbose: Whether output should be verbose.
        :rtype: None
        z# Input:#z (z)::N)printr   rb   r_   rE   )r   ra   verboserg   s       r   _trace_applyzRegexpChunkParser._trace_apply  so     	jhKKDJJx c4::<$.d;dBCc4::<#-.(O  r   c                 H    | j                   D ]  }|j                  |        y)z
        Apply each rule of this ``RegexpChunkParser`` to ``chunkstr``, in
        turn.

        :param chunkstr: The chunk string to which each rule should be
            applied.
        :type chunkstr: ChunkString
        :rtype: None
        N)r   rb   )r   ra   rg   s      r   _notrace_applyz RegexpChunkParser._notrace_apply  s     KKDJJx   r   Nc                    t        |      dk(  r!t        d       t        | j                  g       S 	 |j	                          || j                  }t        |      }|r|dkD  }| j                  ||       n| j                  |       |j                  | j                        S # t
        $ r t        | j                  |      }Y w xY w)aP  
        :type chunk_struct: Tree
        :param chunk_struct: the chunk structure to be (further) chunked
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.  This value
            overrides the trace level value that was given to the
            constructor.
        :rtype: Tree
        :return: a chunk structure that encodes the chunks in a given
            tagged sentence.  A chunk is a non-overlapping linguistic
            group, such as a noun phrase.  The set of chunks
            identified in the chunk structure depends on the rules
            used to define this ``RegexpChunkParser``.
        r   zWarning: parsing empty textr   )r'   r   r   r   r   AttributeErrorr   r   r   r   r>   r   )r   r   r   ra   r   s        r   parsezRegexpChunkParser.parse  s    $ |!/0(("--	@ 
 =KKE|, aiGh0) &&t'8'899#  	@ 0 0,?L	@s   B   CCc                     | j                   S )zu
        :return: the sequence of rules used by ``RegexpChunkParser``.
        :rtype: list(RegexpChunkRule)
        )r   rF   s    r   r   zRegexpChunkParser.rulesH  s    
 {{r   c                 2    dt        | j                        z  S )zy
        :return: a concise string representation of this
            ``RegexpChunkParser``.
        :rtype: str
        z!<RegexpChunkParser with %d rules>)r'   r   rF   s    r   rG   zRegexpChunkParser.__repr__O  s     3S5EEEr   c                 F   dt        | j                        z  }d}| j                  D ]%  }t        |t        |j                                     }' |dk  rdt	        |dz          z   dz   }nd}| j                  D ]#  }|||j                         t	        |      fz  z  }% |dd	 S )
zm
        :return: a verbose string representation of this ``RegexpChunkParser``.
        :rtype: str
        z!RegexpChunkParser with %d rules:
r   #   z    %   zs%s
z    %s
      %s
Nr!   )r'   r   maxr_   rE   )r   r+   marginrg   r   s        r   rK   zRegexpChunkParser.__str__W  s    
 13t{{3CCKKDTZZ\!23F  B;tfqjM22W<F)FKKD4::<d444A  "vr   )NPSr   N)rM   rN   rO   rP   r   r   r   r   r   rG   rK   rX   r   r   r   r     s,    *&4.!):VFr   r   c                   8    e Zd ZdZd	dZd Zd Zd
dZd Zd Z	y)RegexpParsera  
    A grammar based chunk parser.  ``chunk.RegexpParser`` uses a set of
    regular expression patterns to specify the behavior of the parser.
    The chunking of the text is encoded using a ``ChunkString``, and
    each rule acts by modifying the chunking in the ``ChunkString``.
    The rules are all implemented using regular expression matching
    and substitution.

    A grammar contains one or more clauses in the following form::

     NP:
       {<DT|JJ>}          # chunk determiners and adjectives
       }<[\.VI].*>+{      # strip any tag beginning with V, I, or .
       <.*>}{<DT>         # split a chunk at a determiner
       <DT|JJ>{}<NN.*>    # merge chunk ending with det/adj
                          # with one starting with a noun

    The patterns of a clause are executed in order.  An earlier
    pattern may introduce a chunk boundary that prevents a later
    pattern from executing.  Sometimes an individual pattern will
    match on multiple, overlapping extents of the input.  As with
    regular expression substitution more generally, the chunker will
    identify the first match possible, then continue looking for matches
    after this one has ended.

    The clauses of a grammar are also executed in order.  A cascaded
    chunk parser is one having more than one clause.  The maximum depth
    of a parse tree created by this chunk parser is the same as the
    number of clauses in the grammar.

    When tracing is turned on, the comment portion of a line is displayed
    each time the corresponding pattern is applied.

    :type _start: str
    :ivar _start: The start symbol of the grammar (the root node of
        resulting trees)
    :type _stages: int
    :ivar _stages: The list of parsing stages corresponding to the grammar

    c                 ,   || _         g | _        || _        || _        t	        |t
              r| j                  |||       yd}	 t        |      }|D ]  }t	        |t              rt        |       || _        y# t        $ r}t        |      |d}~ww xY w)a  
        Create a new chunk parser, from the given start state
        and set of chunk patterns.

        :param grammar: The grammar, or a list of RegexpChunkParser objects
        :type grammar: str or list(RegexpChunkParser)
        :param root_label: The top node of the tree being created
        :type root_label: str or Nonterminal
        :param loop: The number of times to run through the patterns
        :type loop: int
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.
        z>Expected string or list of RegexpChunkParsers for the grammar.N)r   _stages_grammar_loopr   rJ   _read_grammarr   BaseException	TypeErrorr   )r   grammarr   loopr   type_errrw   elts           r   r   zRegexpParser.__init__  s    " 
gs#w
E: T 1w- !#'89#H--  #DL ! 1)q01s   A9 9	BBBc                    g }d}t        j                  d      }|j                  d      D ]  }|j                         }|j	                  |      }|rT| j                  ||||       |j                  d      j                         }g }|j                  d      j                         }|dk(  s|j                  d      r|j                  t        j                  |              | j                  ||||       y)z[
        Helper function for __init__: read the grammar if it is a
        string.
        Nz*(?P<nonterminal>(\.|[^:])*)(:(?P<rule>.*))
nonterminalrg   r    r   )regexrW   r*   rl   r#   
_add_stagerk   
startswithr7   rZ   rx   )	r   r   r   r   r   lhsre   liners   s	            r   r   zRegexpParser._read_grammar  s    
 -- MNMM$'D::<D d#AsJ>ggm,224wwv,,. rzT__S1 LL33D9:% (* 	sJ6r   c                 ~    |g k7  r8|st        d      t        ||||      }| j                  j                  |       yy)zN
        Helper function for __init__: add a new stage to the parser.
        zExpected stage marker (eg NP:))r8   r   r   N)r   r   r   r7   )r   r   r   r   r   parsers         r   r   zRegexpParser._add_stage  sF     B; !ABB&3:UF LL' r   Nc                     || j                   }t        | j                        D ]&  }| j                  D ]  }|j	                  ||      } ( |S )a  
        Apply the chunk parser to this input.

        :type chunk_struct: Tree
        :param chunk_struct: the chunk structure to be (further) chunked
            (this tree is modified, and is also returned)
        :type trace: int
        :param trace: The level of tracing that should be used when
            parsing a text.  ``0`` will generate no tracing output;
            ``1`` will generate normal tracing output; and ``2`` or
            higher will generate verbose tracing output.  This value
            overrides the trace level value that was given to the
            constructor.
        :return: the chunked output.
        :rtype: Tree
        r   )r   r&   r   r   r   )r   r   r   r.   r   s        r   r   zRegexpParser.parse  sM    " =KKEtzz"A,,%||L|F ' # r   c                 2    dt        | j                        z  S )zn
        :return: a concise string representation of this ``chunk.RegexpParser``.
        :rtype: str
        z#<chunk.RegexpParser with %d stages>r'   r   rF   s    r   rG   zRegexpParser.__repr__  s    
 5s4<<7HHHr   c                 r    dt        | j                        z  }d}| j                  D ]
  }|d|z  z  } |dd S )zt
        :return: a verbose string representation of this
            ``RegexpParser``.
        :rtype: str
        z#chunk.RegexpParser with %d stages:
r   z%s
Nr!   r   )r   r+   r   r   s       r   rK   zRegexpParser.__str__  sC     3S5FFllF& A #"vr   )r   r   r   r   )
rM   rN   rO   rP   r   r   r   r   rG   rK   rX   r   r   r   r   n  s(    'R$#L7>
(0I
r   r   c           
         ddl m} ddlm} |j	                         }|j                  d      D ]w  }t        |       |j                         }|s!|j                  |      }|j                         }| j                   |d|      d      }|j                  ||       t                y t        d       t        d	|        t        d
       t        d|j                         dz  z  dd       t        d|j                         dz  z  dd       t        d|j                         dz  z         |j                         rut        d       |j                         }	|	dd D ]+  }t        ddj!                  t#        t$        |                   - t'        |j                               dkD  rt        d       |j)                         rut        d       |j)                         }
|
dd D ]+  }t        ddj!                  t#        t$        |                   - t'        |j)                               dkD  rt        d       t        d       t                y)a  
    Demonstration code for evaluating a chunk parser, using a
    ``ChunkScore``.  This function assumes that ``text`` contains one
    sentence per line, and that each sentence has the form expected by
    ``tree.chunk``.  It runs the given chunk parser on each sentence in
    the text, and scores the result.  It prints the final score
    (precision, recall, and f-measure); and reports the set of chunks
    that were missed and the set of chunks that were incorrect.  (At
    most 10 missing chunks and 10 incorrect chunks are reported).

    :param chunkparser: The chunkparser to be tested
    :type chunkparser: ChunkParserI
    :param text: The chunked tagged text that should be used for
        evaluation.
    :type text: str
    r   )rv   r   r   r   r   r   zM/===========================================================================\ScoringzM-----------------------------------------------------------------------------zPrecision: %5.1f%%d   z    rI   )endzRecall: %5.1f%%z      zF-Measure: %5.1f%%zMissed:N
   z  z  ...z
Incorrect:zM\===========================================================================/)nltkrv   	nltk.treer   
ChunkScorer*   r   rl   tagstr2treeleavesr   score	precisionrecall	f_measuremissedr   maprJ   r'   	incorrect)chunkparsertextrv   r   
chunkscoresentencegoldtokenstestr  r  s              r   	demo_evalr    s   "  !!#JJJt$h>>#  *  c6!2! <t$ % 

!"	)[!	(O	
*"6"6"83">
?cR	
z002S8
97L	
*"6"6"83">
?@ i""$CR[E$S%12 !z  "#b('N l((*	s^E$S%12 $z##%&+'N	
!"	Gr   c            	      ^   ddl m} m} d}t        d       t        d       t        |       t        d       t                d}|j	                  |      }t        ||       d}|j	                  |      }t        ||       d}|j	                  |      }t        ||       d	}|j	                  |      }t        ||       dd
lm} t                t        d       |j	                  d      }t        |j                  ||j                  dd                   t                t        d       d}|j	                  |      }t        |j                  ||j                  d      dd              t                t        d       d	}|j	                  |      }t        |j                  g d             y)z
    A demonstration for the ``RegexpChunkParser`` class.  A single text is
    parsed with four different chunk parsers, using a variety of rules
    and strategies.
    r   )r   rv   z    [ the/DT little/JJ cat/NN ] sat/VBD on/IN [ the/DT mat/NN ] ./.
    [ John/NNP ] saw/VBD [the/DT cats/NNS] [the/DT dog/NN] chased/VBD ./.
    [ John/NNP ] thinks/VBZ [ Mary/NN ] saw/VBD [ the/DT cat/NN ] sit/VB on/IN [ the/DT mat/NN ]./.
    zK***************************************************************************zEvaluation text:z
    NP:                   # NP stage
      {<DT>?<JJ>*<NN>}    # chunk determiners, adjectives and nouns
      {<NNP>+}            # chunk proper nouns
    z
    NP:
      {<.*>}              # start by chunking each tag
      }<[\.VI].*>+{       # unchunk any verbs, prepositions or periods
      <DT|JJ>{}<NN.*>     # merge det/adj with nouns
    zy
    NP: {<DT>?<JJ>*<NN>}    # chunk determiners, adjectives and nouns
    VP: {<TO>?<VB.*>}       # VP = verb words
    a6  
    NP: {<.*>*}             # start by chunking everything
        }<[\.VI].*>+{       # strip any verbs, prepositions or periods
        <.*>}{<DT>          # separate on determiners
    PP: {<IN><NP>}          # PP = preposition + noun phrase
    VP: {<VB.*><NP|PP>*}    # VP = verb words + NPs and PPs
    )	conll2000zDemonstration of empty grammar:r    ztest.txt)r   )chunk_typesz6Demonstration of accuracy evaluation using CoNLL tags:N   z#Demonstration of tagged token input)theDT)littleJJ)catNN)satVBD)onINr  )matr  ).r  )r   r   rv   r   r   r  nltk.corpusr  accuracychunked_sentsr   )r   rv   r  r   cpr  s         r   demor"  Y  s    !D 
(O	
	$K	(O	GG
 
		G	$Bb$G 
		G	$Bb$G 
		G	$Bb$G 
		G	$Bb$ &	G	
+,			B	B	%..Y44ZW4U
VW	G	
BCG 
		G	$B	%..Y44Z@!D
EF	G	
/0G 
		G	$B	
		
r   __main__)r)   r   nltk.chunk.apir   r   r   r   rZ   rm   rn   r   rp   ro   r   r   rq   rW   r   r   r~   r   r   r  r"  rM   rX   r   r   <module>r%     s
   
  ' d dXJH JHZ): ):X*: *:Z%</ %<PC
 C
LB
 B
JC
_ C
LC
o C
LO
? O
p BJJBMR 
=J^ ^Ld< dX<~eP zF r   