
    /h                        S SK r S SKrS SKJr  S SKJr   " S S5      r " S S5      r " S S	\5      r " S
 S\5      r	 " S S\5      r
 " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r\ R                   " SR#                  SS5      5      rS r " S S\5      r " S S\5      rS  rS! r\S":X  a  \" 5         gg)#    N)ChunkParserITreec                       \ rS rSrSrSrS\-  rSrSrS\-  r	S\-  r
\R                  " S	\-  5      r\R                  " S
5      r\R                  " S5      rSS jrS rS rSS jrS rS rS rSrg)ChunkString   a  
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                     UR                  5       U l        USS U l        U R                   Vs/ s H  o0R                  U5      PM     nnSSR	                  U5      -   S-   U l        X l        gs  snf )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        I/var/www/auris/envauris/lib/python3.13/site-packages/nltk/chunk/regexp.py__init__ChunkString.__init__H   sa    . (--/#A*.,,7,3		#,7$))D/)C/	! 8s   A-c                     [        U[        5      (       a  US   $ [        U[        5      (       a  UR                  5       $ [	        S5      e)N   z4chunk structures must contain tagged tokens or trees)
isinstancetupler   r   
ValueError)r   r   s     r   r   ChunkString._tage   s=    c5!!q6MT""99;VWW    c                 (   [         R                  R                  U5      (       d  [        SU-  5      e[         R                  R                  SU5      n[        S[        U5      S-  -   5       HB  nX4S-  US-  S-    n[         R                  R                  U5      (       a  M6  [        SU-  5      e   US::  a  g[        R                  " SU5      SS nU R                   Vs/ s H  opR                  U5      PM     nnXh:w  a  [        S	5      egs  snf )
a4  
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   _verifyChunkString._verifym   s   " !!''**H1L  ((,,R3q3x=D001A$hTD9F1177?? LqP  2 !,*Ab1/3||<|e5!|<>N   =s   "Dc                    U R                   S:  a  U R                  U R                  S5        / nSnSn[        R                  " SU R                  5       HV  nUR                  S5      nU R                  X3U-    nU(       a  UR                  [        X5      5        OX'-  nX6-  nU(       + nMX     [        U R                  U5      $ )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   r6   r   r,   r-   countr   appendr   r   )r   chunk_labelpiecesindexpiece_in_chunkr4   lengthsubsequences           r   to_chunkstructChunkString.to_chunkstruct   s     ;;?LLA& XXfdii0E[[%F,,uv~>K d;<=% OE!//N 1 D$$f--r!   c                     [         R                  " XU R                  5      n[         R                  " SSU5      nU R                  S:  a  U R	                  X0R                  S-
  5        X0l        g)a  
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   r6   )r   regexpreplr.   s       r   xformChunkString.xform   sT    4 FF6+
 FF7B" ;;?LLKK!O, 	r!   c                 2    S[        U R                  5      -  $ )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__ChunkString.__repr__   s     #T$))_44r!   c                     [         R                  " SSU R                  5      n[         R                  " SSU5      nUS   S:X  a  SU-   nU$ )z
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__ChunkString.__str__   sE     ffZ		2ff['3/q6S=)C
r!   )r   r   r   r   N)r   )CHUNK)__name__
__module____qualname____firstlineno____doc__CHUNK_TAG_CHAR	CHUNK_TAGIN_CHUNK_PATTERNIN_STRIP_PATTERN_CHUNK_STRIPr,   compiler%   r'   r+   r   r   r6   rB   rH   rM   rR   __static_attributes__ r!   r   r   r      s    #J "Nn,I&* y(F9$FZZ)I56F

;'IK0":X)V.@&P	5r!   r   c                   @    \ rS rSrSrS rS rS rS r\	S 5       r
Srg	)
RegexpChunkRulei  a[  
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                 ~    [        U[        5      (       a  [        R                  " U5      nX l        X0l        Xl        g)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   rQ   r,   r`   _repl_descr_regexp)r   rF   rG   descrs       r   r   RegexpChunkRule.__init__  s.    $ fc""ZZ'F
r!   c                 P    UR                  U R                  U R                  5        g)aD  
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)rH   rh   rf   )r   chunkstrs     r   applyRegexpChunkRule.apply3  s     	t||TZZ0r!   c                     U R                   $ )zT
Return a short description of the purpose and/or effect of
this rule.

:rtype: str
)rg   rL   s    r   ri   RegexpChunkRule.descrB  s     {{r!   c                 ~    S[        U R                  R                  5      -   S-   [        U R                  5      -   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   )rK   rh   patternrf   rL   s    r   rM   RegexpChunkRule.__repr__K  sH     !4<<''() 4:: 		
r!   c                    [         R                  " SU 5      nUR                  S5      R                  5       nUR                  S5      =(       d    SSS R                  5       n U(       d  [	        S5      eUS   S	:X  a  US
   S:X  a  [        USS
 U5      $ US   S:X  a  US
   S	:X  a  [        USS
 U5      $ SU;   a  UR                  S5      u  pE[        XEU5      $ SU;   a  UR                  S5      u  pE[        XEU5      $ [         R                  " SU5      (       a&  [         R                  " SU5      u  pFn[        XFXS5      $ [	        SU-  5      e! [        [         R                  4 a  n[	        SU-  5      UeSnAff = f)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[^{}]*{[^{}]*}[^{}]*r9   zIllegal chunk pattern: %s)r,   r&   groupstripr   	ChunkRule	StripRuler-   	SplitRule	MergeRuleChunkRuleWithContexterror)r.   mru   rv   leftrightchunkes           r   
fromstringRegexpChunkRule.fromstring_  sn   ( 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. g66"jj. g660$77%'XXfd%;"U+DHH !<t!CDDBHH% 	H84?@aG	Hs7   #2E  E 7$E $E AE E E?+E::E?)rg   rh   rf   N)rU   rV   rW   rX   rY   r   rm   ri   rM   staticmethodr   ra   rb   r!   r   rd   rd     s1    201
( +H +Hr!   rd   c                   $    \ rS rSrSrS rS rSrg)r{   i  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                     Xl         [        R                  " S[        U5      < S[        R
                  < 35      n[        R                  XSU5        g)aa  
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,   r`   tag_pattern2re_patternr   r]   rd   r   r   tag_patternri   rF   s       r   r   ChunkRule.__init__  sA     $%k2K4P4PR
 	  ~uEr!   c                 8    S[        U R                  5      -   S-   $ )z
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   rK   r   rL   s    r   rM   ChunkRule.__repr__       T]] 33c99r!   r   NrU   rV   rW   rX   rY   r   rM   ra   rb   r!   r   r{   r{     s    F(:r!   r{   c                   $    \ rS rSrSrS rS rSrg)r|   i  a  
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                     Xl         [        R                  " S[        U5      < S[        R
                  < 35      n[        R                  XSU5        g)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,   r`   r   r   r\   rd   r   r   s       r   r   StripRule.__init__  sA     $%k2K4P4PR
 	  ~uEr!   c                 8    S[        U R                  5      -   S-   $ )z
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   rL   s    r   rM   StripRule.__repr__  r   r!   r   Nr   rb   r!   r   r|   r|     s    F*:r!   r|   c                   $    \ rS rSrSrS rS rSrg)UnChunkRulei  z
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                     Xl         [        R                  " S[        U5      -  5      n[        R                  XSU5        g)aP  
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,   r`   r   rd   r   r   s       r   r   UnChunkRule.__init__  s5     $03I+3VVW  |UCr!   c                 8    S[        U R                  5      -   S-   $ )z
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   rL   s    r   rM   UnChunkRule.__repr__   s      $t}}"55;;r!   r   Nr   rb   r!   r   r   r     s    D"<r!   r   c                   $    \ rS rSrSrS rS rSrg)r~   i  ab  
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                 (   [         R                  " [        U5      5        [         R                  " [        U5      5        Xl        X l        [         R                  " S[        U5      < S[        U5      < S35      n[
        R                  XSU5        g)a2  
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,   r`   r   _left_tag_pattern_right_tag_patternrd   r   r   left_tag_patternright_tag_patternri   rF   s        r   r   MergeRule.__init__  sq    2 	

)*:;<


)*;<=!1"3 ''78&'89
 	  {EBr!   c                 j    S[        U R                  5      -   S-   [        U R                  5      -   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   rK   r   r   rL   s    r   rM   MergeRule.__repr__@  F     4))*+ 4**+, 		
r!   r   r   Nr   rb   r!   r   r~   r~     s    %CN
r!   r~   c                   $    \ rS rSrSrS rS rSrg)r}   iU  a[  
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                 (   [         R                  " [        U5      5        [         R                  " [        U5      5        Xl        X l        [         R                  " S[        U5      < S[        U5      < S35      n[
        R                  XSU5        g)aG  
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   SplitRule.__init___  sq    0 	

)*:;<


)*;<=!1"3 ''78&'89
 	  }eDr!   c                 j    S[        U R                  5      -   S-   [        U R                  5      -   S-   $ )z
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   rL   s    r   rM   SplitRule.__repr__  r   r!   r   Nr   rb   r!   r   r}   r}   U  s    $EL
r!   r}   c                   $    \ rS rSrSrS rS rSrg)ExpandLeftRulei  a  
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                 (   [         R                  " [        U5      5        [         R                  " [        U5      5        Xl        X l        [         R                  " S[        U5      < S[        U5      < S35      n[
        R                  XSU5        g)aJ  
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   ExpandLeftRule.__init__  r    2 	

)*:;<


)*;<=!1"3 ''78&'89
 	  /DeLr!   c                 j    S[        U R                  5      -   S-   [        U R                  5      -   S-   $ )a	  
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   rL   s    r   rM   ExpandLeftRule.__repr__  sF      4))*+ 4**+, 		
r!   r   Nr   rb   r!   r   r   r         %MN
r!   r   c                   $    \ rS rSrSrS rS rSrg)ExpandRightRulei  a  
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                 (   [         R                  " [        U5      5        [         R                  " [        U5      5        Xl        X l        [         R                  " S[        U5      < S[        U5      < S35      n[
        R                  XSU5        g)aK  
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   ExpandRightRule.__init__  r   r!   c                 j    S[        U R                  5      -   S-   [        U R                  5      -   S-   $ )a
  
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   rL   s    r   rM   ExpandRightRule.__repr__  sF     !4))*+ 4**+, 		
r!   r   Nr   rb   r!   r   r   r     r   r!   r   c                   $    \ rS rSrSrS rS rSrg)r   i&  ay  
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           
         [         R                  " [        U5      5        [         R                  " [        U5      5        [         R                  " [        U5      5        Xl        X l        X0l        [         R                  " S[        U5      < S[        U5      < S[        U5      < S[        R                  < 35      nSn[        R                  XXd5        g)a  
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,   r`   r   _left_context_tag_pattern_chunk_tag_pattern_right_context_tag_patternr   r]   rd   r   )r   left_context_tag_patternchunk_tag_patternright_context_tag_patternri   rF   replacements          r   r   ChunkRuleWithContext.__init__6  s    8 	

)*BCD


)*;<=


)*CDE)A&"3*C' ''?@&'89&'@A,,
 6  {Br!   c                 d    SR                  U R                  U R                  U R                  5      $ )a  
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   rL   s    r   rM   ChunkRuleWithContext.__repr__e  s2     ;AA**##++
 	
r!   )r   r   r   Nr   rb   r!   r   r   r   &  s    -C^
r!   r   z^(({}|<{}>)*)$z"([^\{\}<>]|\{\d+,?\}|\{\d*,\d+\})+z
[^\{\}<>]+c                 f   [         R                  " SSU 5      n [         R                  " SSU 5      n [         R                  " SSU 5      n [        R                  U 5      (       d  [	        SU -  5      eS nU" [
        R                  5      nU" U 5      n[         R                  " S	X#5      nU" U5      n U $ )
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    [        U 5      nUR                  5         SR                  U5      $ )Nr#   )listreverser   )rQ   lsts     r   reverse_str+tag_pattern2re_pattern.<locals>.reverse_str  s"    3iwws|r!   z\.(?!\\(\\\\)*($|[^\\])))r,   r(   CHUNK_TAG_PATTERNr&   r   r   rZ   )r   r   tc_revreverseds       r   r   r     s    J &&K0K&&uk2K&&uk2K "";//.<==
 334F;'Hvv16DHh'Kr!   c                   J    \ rS rSrSrSS jrS rS rSS jrS r	S	 r
S
 rSrg)RegexpChunkParseri  a.  
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                 4    Xl         X@l        X l        X0l        g)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   rulesr<   
root_labeltraces        r   r   RegexpChunkParser.__init__  s    * '%r!   c                 0   [        S5        [        U5        U R                   Hp  nUR                  U5        U(       a-  [        SUR                  5       S-   [	        U5      -   S-   5        O[        SUR                  5       S-   5        [        U5        Mr     g)af  
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   rm   ri   rK   )r   rl   verboseru   s       r   _trace_applyRegexpChunkParser._trace_apply  so     	jhKKDJJx c4::<$.d;dBCc4::<#-.(O  r!   c                 L    U R                    H  nUR                  U5        M     g)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   rm   )r   rl   ru   s      r   _notrace_apply RegexpChunkParser._notrace_apply  s     KKDJJx   r!   Nc                    [        U5      S:X  a!  [        S5        [        U R                  / 5      $  UR	                  5         Uc  U R                  n[        U5      nU(       a  US:  nU R                  X45        OU R                  U5        UR                  U R                  5      $ ! [
         a    [        U R                  U5      n Nf = f)a  
: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   rB   r   )r   r   r   rl   r   s        r   parseRegexpChunkParser.parse  s    $ |!/0(("--	@ 
 =KKE|, aiGh0) &&t'8'899#  	@ 0 0,?L	@s   B& & C	C	c                     U R                   $ )z]
:return: the sequence of rules used by ``RegexpChunkParser``.
:rtype: list(RegexpChunkRule)
)r   rL   s    r   r   RegexpChunkParser.rulesH  s    
 {{r!   c                 2    S[        U R                  5      -  $ )zY
:return: a concise string representation of this
    ``RegexpChunkParser``.
:rtype: str
z!<RegexpChunkParser with %d rules>)r*   r   rL   s    r   rM   RegexpChunkParser.__repr__O  s     3S5EEEr!   c                 N   S[        U R                  5      -  nSnU R                   H&  n[        U[        UR                  5       5      5      nM(     US:  a  S[	        US-   * 5      -   S-   nOSnU R                   H#  nXUR                  5       [	        U5      4-  -  nM%     USS	 $ )
zU
: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   maxri   rK   )r   r.   marginru   r   s        r   rR   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!   )r   r   r   r   )NPSr   N)rU   rV   rW   rX   rY   r   r   r   r   r   rM   rR   ra   rb   r!   r   r   r     s,    *&4.!):VFr!   r   c                   D    \ rS rSrSrSS jrS rS rSS jrS r	S	 r
S
rg)RegexpParserin  aw  
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                 <   X@l         / U l        Xl        X0l        [	        U[
        5      (       a  U R                  XU5        gSn [        U5      nU H#  n[	        U[        5      (       a  M  [        U5      e   Xl        g! [         a  n[        U5      UeSnAff = f)ag  
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   rQ   _read_grammarr   BaseException	TypeErrorr   )r   grammarr   loopr   type_errr   elts           r   r   RegexpParser.__init__  s    " 
gs##wE: T 1w- !#'899#H--  #L ! 1)q01s   B   
B
BBc                    / nSn[         R                  " S5      nUR                  S5       H  nUR                  5       nUR	                  U5      nU(       aR  U R                  XEX#5        UR                  S5      R                  5       n/ nUR                  S5      R                  5       nUS:X  d  UR                  S5      (       a  M  UR                  [        R                  U5      5        M     U R                  XEX#5        g)zC
Helper function for __init__: read the grammar if it is a
string.
Nz*(?P<nonterminal>(\.|[^:])*)(:(?P<rule>.*))
nonterminalru   r#   r   )regexr`   r-   rz   r&   
_add_stagery   
startswithr;   rd   r   )	r   r
  r   r   r   lhsrr   liner   s	            r   r  RegexpParser._read_grammar  s    
 -- MNMM$'D::<D d#AJ>ggm,224wwv,,. rzT__S11 LL33D9:% (* 	J6r!   c                     U/ :w  a8  U(       d  [        S5      e[        XX4S9nU R                  R                  U5        gg)z>
Helper function for __init__: add a new stage to the parser.
zExpected stage marker (eg NP:))r<   r   r   N)r   r   r  r;   )r   r   r  r   r   parsers         r   r  RegexpParser._add_stage  sB     B; !ABB&:F LL' r!   Nc                     Uc  U R                   n[        U R                  5       H%  nU R                   H  nUR	                  XS9nM     M'     U$ )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   r1   r  s        r   r   RegexpParser.parse  sK    " =KKEtzz"A,,%||L|F ' # r!   c                 2    S[        U R                  5      -  $ )zV
:return: a concise string representation of this ``chunk.RegexpParser``.
:rtype: str
z#<chunk.RegexpParser with %d stages>r*   r  rL   s    r   rM   RegexpParser.__repr__  s    
 5s4<<7HHHr!   c                 v    S[        U R                  5      -  nSnU R                   H  nUSU-  -  nM     US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   rR   RegexpParser.__str__  sC     3S5FFllF& A #"vr!   )r  r  r  r   )r   r   r   r   )rU   rV   rW   rX   rY   r   r  r  r   rM   rR   ra   rb   r!   r   r  r  n  s(    'R$#L7>
(0I
r!   r  c           
         SSK Jn  SSKJn  UR	                  5       nUR                  S5       Hz  n[        U5        UR                  5       nU(       d  M'  UR                  U5      nUR                  5       nU R                  U" SU5      SS9nUR                  Xh5        [        5         M|     [        S5        [        S	U 5        [        S
5        [        SUR                  5       S-  -  SSS9  [        SUR                  5       S-  -  SSS9  [        SUR                  5       S-  -  5        UR                  5       (       ax  [        S5        UR                  5       n	U	SS  H,  n[        SSR!                  [#        [$        U5      5      5        M.     ['        UR                  5       5      S:  a  [        S5        UR)                  5       (       ax  [        S5        UR)                  5       n
U
SS  H,  n[        SSR!                  [#        [$        U5      5      5        M.     ['        UR)                  5       5      S:  a  [        S5        [        S5        [        5         g)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   )r   r   r  r   r   r  zM/===========================================================================\ScoringzM-----------------------------------------------------------------------------zPrecision: %5.1f%%d   z    rP   )endzRecall: %5.1f%%z      zF-Measure: %5.1f%%zMissed:N
   z  z  ...z
Incorrect:zM\===========================================================================/)nltkr   	nltk.treer   
ChunkScorer-   r   rz   tagstr2treeleavesr   score	precisionrecall	f_measuremissedr   maprQ   r*   	incorrect)chunkparsertextr   r   
chunkscoresentencegoldtokenstestr1  r3  s              r   	demo_evalr;    s   "  !!#JJJt$h>>#  *  c6!2! <$ % 

!"	)[!	(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            
      L   SSK Jn Jn  Sn[        S5        [        S5        [        U5        [        S5        [        5         SnUR	                  U5      n[        XB5        SnUR	                  U5      n[        XB5        SnUR	                  U5      n[        XB5        S	nUR	                  U5      n[        XB5        SS
KJn  [        5         [        S5        UR	                  S5      n[        UR                  XER                  SSS95      5        [        5         [        S5        SnUR	                  U5      n[        UR                  XER                  S5      SS 5      5        [        5         [        S5        S	nUR	                  U5      n[        UR                  / SQ5      5        g)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   r   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@  )matrF  ).rL  )r(  r   r   r   r  r;  nltk.corpusr=  accuracychunked_sentsr   )r   r   r5  r
  cpr=  s         r   demorQ  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	%..44ZW4U
VW	G	
BCG 
		G	$B	%..44Z@!D
EF	G	
/0G 
		G	$B	
		
r!   __main__)r,   r  nltk.chunk.apir   r)  r   r   rd   r{   r|   r   r~   r}   r   r   r   r`   r   r   r   r   r  r;  rQ  rU   rb   r!   r   <module>rT     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 JJBMR 
=J^ ^Ld< dX<~eP zF r!   