
    g                     T    d Z ddlZddlmZmZ ddlmZ  G d de      Zd Z	d Z
dgZy)	zh
Class for representing hierarchical language structures, such as
syntax trees and morphological trees.
    N)Nonterminal
Production)
deprecatedc                      e Zd ZdZd5dZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zd Zd Z ed      d        Z ed      d        Z eee      Zd Zd Zd Zd Zd Zd6dZd5dZd Zd Zd Z d Z!	 	 	 	 	 d7d Z"	 d8d!Z#d9d"Z$e%d#        Z&d$ Z'd% Z(d:d&Z)d' Z*d5d(Z+e%	 	 	 	 	 	 d;d)       Z,e%d*        Z-e%d+        Z.d, Z/d<d-Z0d. Z1d/ Z2d0 Z3d1 Z4d=d2Z5d3 Z6d4 Z7y)>Treeai  
    A Tree represents a hierarchical grouping of leaves and subtrees.
    For example, each constituent in a syntax tree is represented by a single Tree.

    A tree's children are encoded as a list of leaves and subtrees,
    where a leaf is a basic (non-tree) value; and a subtree is a
    nested Tree.

        >>> from nltk.tree import Tree
        >>> print(Tree(1, [2, Tree(3, [4]), 5]))
        (1 2 (3 4) 5)
        >>> vp = Tree('VP', [Tree('V', ['saw']),
        ...                  Tree('NP', ['him'])])
        >>> s = Tree('S', [Tree('NP', ['I']), vp])
        >>> print(s)
        (S (NP I) (VP (V saw) (NP him)))
        >>> print(s[1])
        (VP (V saw) (NP him))
        >>> print(s[1,1])
        (NP him)
        >>> t = Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))")
        >>> s == t
        True
        >>> t[1][1].set_label('X')
        >>> t[1][1].label()
        'X'
        >>> print(t)
        (S (NP I) (VP (V saw) (X him)))
        >>> t[0], t[1,1] = t[1,1], t[0]
        >>> print(t)
        (S (X him) (VP (V saw) (NP I)))

    The length of a tree is the number of children it has.

        >>> len(t)
        2

    The set_label() and label() methods allow individual constituents
    to be labeled.  For example, syntax trees use this label to specify
    phrase tags, such as "NP" and "VP".

    Several Tree methods use "tree positions" to specify
    children or descendants of a tree.  Tree positions are defined as
    follows:

      - The tree position *i* specifies a Tree's *i*\ th child.
      - The tree position ``()`` specifies the Tree itself.
      - If *p* is the tree position of descendant *d*, then
        *p+i* specifies the *i*\ th child of *d*.

    I.e., every tree position is either a single index *i*,
    specifying ``tree[i]``; or a sequence *i1, i2, ..., iN*,
    specifying ``tree[i1][i2]...[iN]``.

    Construct a new tree.  This constructor can be called in one
    of two ways:

    - ``Tree(label, children)`` constructs a new tree with the
        specified label and list of children.

    - ``Tree.fromstring(s)`` constructs a new tree by parsing the string ``s``.
    Nc                     |!t        dt        |       j                  z        t        |t              r!t        dt        |       j                  z        t
        j                  | |       || _        y )Nz)%s: Expected a node value and child list z.%s() argument 2 should be a list, not a string)	TypeErrortype__name__
isinstancestrlist__init___label)selfnodechildrens      C/var/www/openai/venv/lib/python3.12/site-packages/nltk/tree/tree.pyr   zTree.__init__\   sn    ;d4j>Q>QQ  #&:../ 
 MM$)DK    c                     | j                   |j                   u xr/ | j                  t        |       f|j                  t        |      fk(  S N)	__class__r   r   r   others     r   __eq__zTree.__eq__n   sD    ~~0 
dkk4:5NLLKS
 6
 	
r   c                 d   t        |t              s-| j                  j                  |j                  j                  k  S | j                  |j                  u r/| j                  t        |       f|j                  t        |      fk  S | j                  j                  |j                  j                  k  S r   )r   r   r   r   r   r   r   s     r   __lt__zTree.__lt__t   s    %& >>**U__-E-EEE^^u.KKd,d5k/JJJ>>**U__-E-EEEr   c                     | |k(   S r    r   s     r   <lambda>zTree.<lambda>   s    TU]!2r   c                     | |k  xs | |k(   S r   r   r   s     r   r    zTree.<lambda>   s    dUl&Cdem!Dr   c                     | |k  xs | |k(  S r   r   r   s     r   r    zTree.<lambda>   s    !>!>r   c                     | |k   S r   r   r   s     r   r    zTree.<lambda>   s    TE\!1r   c                     t        d      Nz$Tree does not support multiplicationr	   r   vs     r   __mul__zTree.__mul__       >??r   c                     t        d      r%   r&   r'   s     r   __rmul__zTree.__rmul__   r*   r   c                     t        d      NzTree does not support additionr&   r'   s     r   __add__zTree.__add__       899r   c                     t        d      r.   r&   r'   s     r   __radd__zTree.__radd__   r0   r   c                 Z   t        |t        t        f      rt        j	                  | |      S t        |t        t
        f      r4t        |      dk(  r| S t        |      dk(  r| |d      S | |d      |dd     S t        t        |       j                  dt        |      j                        )Nr       indices must be integers, not )
r   intslicer   __getitem__tuplelenr	   r
   r   r   indexs     r   r8   zTree.__getitem__   s    ec5\*##D%00e}-5zQUqE!H~%E!H~eABi00:&&U(<(<> r   c                 r   t        |t        t        f      rt        j	                  | ||      S t        |t        t
        f      r?t        |      dk(  rt        d      t        |      dk(  r	|| |d   <   y || |d      |dd  <   y t        t        |       j                  dt        |      j                        )Nr   z,The tree position () may not be assigned to.r4   r5   )r   r6   r7   r   __setitem__r9   r:   
IndexErrorr	   r
   r   )r   r<   values      r   r>   zTree.__setitem__   s    ec5\*##D%77e}-5zQ !RSSUq!&U1X,1U1XuQRy):&&U(<(<> r   c                 h   t        |t        t        f      rt        j	                  | |      S t        |t        t
        f      r;t        |      dk(  rt        d      t        |      dk(  r| |d   = y | |d      |dd  = y t        t        |       j                  dt        |      j                        )Nr   z(The tree position () may not be deleted.r4   r5   )r   r6   r7   r   __delitem__r9   r:   r?   r	   r
   r   r;   s     r   rB   zTree.__delitem__   s    ec5\*##D%00e}-5zQ !KLLUqqNqN59-:&&U(<(<> r   zUse label() insteadc                      y)zIOutdated method to access the node value; use the label() method instead.Nr   r   s    r   	_get_nodezTree._get_node       r   zUse set_label() insteadc                      y)zJOutdated method to set the node value; use the set_label() method instead.Nr   )r   r@   s     r   	_set_nodezTree._set_node   rF   r   c                     | j                   S )a  
        Return the node label of the tree.

            >>> t = Tree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))')
            >>> t.label()
            'S'

        :return: the node label (typically a string)
        :rtype: any
        r   rD   s    r   labelz
Tree.label   s     {{r   c                     || _         y)ao  
        Set the node label of the tree.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.set_label("T")
            >>> print(t)
            (T (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))

        :param label: the node label (typically a string)
        :type label: any
        NrJ   )r   rK   s     r   	set_labelzTree.set_label   s     r   c                     g }| D ]C  }t        |t              r |j                  |j                                3|j	                  |       E |S )a  
        Return the leaves of the tree.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.leaves()
            ['the', 'dog', 'chased', 'the', 'cat']

        :return: a list containing this tree's leaves.
            The order reflects the order of the
            leaves in the tree's hierarchical structure.
        :rtype: list
        )r   r   extendleavesappend)r   rP   childs      r   rP   zTree.leaves   sB     E%&elln-e$	 
 r   c                 R    t        | j                         | j                               S )a  
        Return a flat version of the tree, with all non-root non-terminals removed.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> print(t.flatten())
            (S the dog chased the cat)

        :return: a tree consisting of this tree's root connected directly to
            its leaves, omitting all intervening non-terminal nodes.
        :rtype: Tree
        )r   rK   rP   rD   s    r   flattenzTree.flatten  s     DJJL$++-00r   c                     d}| D ]9  }t        |t              rt        ||j                               }.t        |d      }; d|z   S )aG  
        Return the height of the tree.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.height()
            5
            >>> print(t[0,0])
            (D the)
            >>> t[0,0].height()
            2

        :return: The height of this tree.  The height of a tree
            containing no children is 1; the height of a tree
            containing only leaves is 2; and the height of any other
            tree is one plus the maximum of its children's
            heights.
        :rtype: int
        r   r4   )r   r   maxheight)r   max_child_heightrR   s      r   rW   zTree.height  sN    & E%&#&'7#H #&'7#; 	 
 ###r   c                 "   g }|dv r|j                  d       t        |       D ]S  \  }t        |t              r,|j	                  |      }|j                  fd|D               B|j                  f       U |dv r|j                  d       |S )a.  
            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.treepositions() # doctest: +ELLIPSIS
            [(), (0,), (0, 0), (0, 0, 0), (0, 1), (0, 1, 0), (1,), (1, 0), (1, 0, 0), ...]
            >>> for pos in t.treepositions('leaves'):
            ...     t[pos] = t[pos][::-1].upper()
            >>> print(t)
            (S (NP (D EHT) (N GOD)) (VP (V DESAHC) (NP (D EHT) (N TAC))))

        :param order: One of: ``preorder``, ``postorder``, ``bothorder``,
            ``leaves``.
        )preorder	bothorderr   c              3   *   K   | ]
  }f|z     y wr   r   ).0pis     r   	<genexpr>z%Tree.treepositions.<locals>.<genexpr>B  s      <8a!8s   )	postorderr[   )rQ   	enumerater   r   treepositionsrO   )r   order	positionsrR   childposr_   s        @r   rc   zTree.treepositions/  s     	--R !$HAu%& ..u5   <8 <<  !& ( ..R r   c              #      K   |r ||       r|  | D ],  }t        |t              s|j                  |      E d{    . y7 w)a  
        Generate all the subtrees of this tree, optionally restricted
        to trees matching the filter function.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> for s in t.subtrees(lambda t: t.height() == 2):
            ...     print(s)
            (D the)
            (N dog)
            (V chased)
            (D the)
            (N cat)

        :type filter: function
        :param filter: the function to filter all local trees
        N)r   r   subtrees)r   filterrR   s      r   rh   zTree.subtreesI  s?     " JE%& >>&111 1s   $AAAAc                     t        | j                  t              st        d      t	        t        | j                        t        |             g}| D ]&  }t        |t              s||j                         z  }( |S )a)  
        Generate the productions that correspond to the non-terminal nodes of the tree.
        For each subtree of the form (P: C1 C2 ... Cn) this produces a production of the
        form P -> C1 C2 ... Cn.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.productions() # doctest: +NORMALIZE_WHITESPACE
            [S -> NP VP, NP -> D N, D -> 'the', N -> 'dog', VP -> V NP, V -> 'chased',
            NP -> D N, D -> 'the', N -> 'cat']

        :rtype: list(Production)
        zPProductions can only be generated from trees having node labels that are strings)	r   r   r   r	   r   r   _child_namesr   productions)r   prodsrR   s      r   rl   zTree.productions`  so     $++s+b  K4l46HIJE%&**,,  r   c                     g }| D ]O  }t        |t              r |j                  |j                                3|j	                  || j
                  f       Q |S )a  
        Return a sequence of pos-tagged words extracted from the tree.

            >>> t = Tree.fromstring("(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))")
            >>> t.pos()
            [('the', 'D'), ('dog', 'N'), ('chased', 'V'), ('the', 'D'), ('cat', 'N')]

        :return: a list of tuples containing leaves and pre-terminals (part-of-speech tags).
            The order reflects the order of the leaves in the tree's hierarchical structure.
        :rtype: list(tuple)
        )r   r   rO   posrQ   r   )r   ro   rR   s      r   ro   zTree.posy  sK     E%&

599;'

E4;;/0	 
 
r   c                    |dk  rt        d      | dfg}|rk|j                         \  }}t        |t              s|dk(  r|S |dz  }n8t	        t        |      dz
  dd      D ]  }|j                  ||   ||fz   f        |rkt        d      )a,  
        :return: The tree position of the ``index``-th leaf in this
            tree.  I.e., if ``tp=self.leaf_treeposition(i)``, then
            ``self[tp]==self.leaves()[i]``.

        :raise IndexError: If this tree contains fewer than ``index+1``
            leaves, or if ``index<0``.
        r   zindex must be non-negativer   r4   z-index must be less than or equal to len(self))r?   popr   r   ranger:   rQ   )r   r<   stackr@   treeposr_   s         r   leaf_treepositionzTree.leaf_treeposition  s     199::"YY[NE7eT*A:"NQJEs5zA~r26ALL%(GqdN!;< 7  HIIr   c                     ||k  rt        d      | j                  |      }| j                  |dz
        }t        t        |            D ]"  }|t        |      k(  s||   ||   k7  s|d| c S  |S )z
        :return: The tree position of the lowest descendant of this
            tree that dominates ``self.leaves()[start:end]``.
        :raise ValueError: if ``end <= start``
        zend must be greater than startr4   N)
ValueErrorrv   rs   r:   )r   startendstart_treeposend_treeposr_   s         r   treeposition_spanning_leavesz!Tree.treeposition_spanning_leaves  s     %<=>> ..u5,,S1W5s=)*AC$$a(8KN(J$Ra(( + r   c                 *    ddl m}  || |||||       y)a  
        This method can modify a tree in three ways:

          1. Convert a tree into its Chomsky Normal Form (CNF)
             equivalent -- Every subtree has either two non-terminals
             or one terminal as its children.  This process requires
             the creation of more"artificial" non-terminal nodes.
          2. Markov (vertical) smoothing of children in new artificial
             nodes
          3. Horizontal (parent) annotation of nodes

        :param factor: Right or left factoring method (default = "right")
        :type  factor: str = [left|right]
        :param horzMarkov: Markov order for sibling smoothing in artificial nodes (None (default) = include all siblings)
        :type  horzMarkov: int | None
        :param vertMarkov: Markov order for parent smoothing (0 (default) = no vertical annotation)
        :type  vertMarkov: int | None
        :param childChar: A string used in construction of the artificial nodes, separating the head of the
                          original subtree from the child nodes that have yet to be expanded (default = "|")
        :type  childChar: str
        :param parentChar: A string used to separate the node representation from its vertical annotation
        :type  parentChar: str
        r   )chomsky_normal_formN)nltk.tree.transformsr   )r   factor
horzMarkov
vertMarkov	childChar
parentCharr   s          r   r   zTree.chomsky_normal_form  s    > 	=D&*j)ZXr   c                 (    ddl m}  || ||||       y)am  
        This method modifies the tree in three ways:

          1. Transforms a tree in Chomsky Normal Form back to its
             original structure (branching greater than two)
          2. Removes any parent annotation (if it exists)
          3. (optional) expands unary subtrees (if previously
             collapsed with collapseUnary(...) )

        :param expandUnary: Flag to expand unary or not (default = True)
        :type  expandUnary: bool
        :param childChar: A string separating the head node from its children in an artificial node (default = "|")
        :type  childChar: str
        :param parentChar: A string separating the node label from its parent annotation (default = "^")
        :type  parentChar: str
        :param unaryChar: A string joining two non-terminals in a unary production (default = "+")
        :type  unaryChar: str
        r   )un_chomsky_normal_formN)r   r   )r   expandUnaryr   r   	unaryCharr   s         r   r   zTree.un_chomsky_normal_form  s    * 	@t[)ZSr   c                 &    ddl m}  || |||       y)a  
        Collapse subtrees with a single child (ie. unary productions)
        into a new non-terminal (Tree node) joined by 'joinChar'.
        This is useful when working with algorithms that do not allow
        unary productions, and completely removing the unary productions
        would require loss of useful information.  The Tree is modified
        directly (since it is passed by reference) and no value is returned.

        :param collapsePOS: 'False' (default) will not collapse the parent of leaf nodes (ie.
                            Part-of-Speech tags) since they are always unary productions
        :type  collapsePOS: bool
        :param collapseRoot: 'False' (default) will not modify the root production
                             if it is unary.  For the Penn WSJ treebank corpus, this corresponds
                             to the TOP -> productions.
        :type collapseRoot: bool
        :param joinChar: A string used to connect collapsed node values (default = "+")
        :type  joinChar: str
        r   )collapse_unaryN)r   r   )r   collapsePOScollapseRootjoinCharr   s        r   r   zTree.collapse_unary  s    & 	8t[,Ar   c                     t        |t              r1|D cg c]  }| j                  |       }} | |j                  |      S |S c c}w )a  
        Convert a tree between different subtypes of Tree.  ``cls`` determines
        which class will be used to encode the new tree.

        :type tree: Tree
        :param tree: The tree that should be converted.
        :return: The new Tree.
        )r   r   convertr   )clstreerR   r   s       r   r   zTree.convert  sF     dD!8<=uE*H=t{{H--K >s   Ac                 "    | j                         S r   copyrD   s    r   __copy__zTree.__copy__$  s    yy{r   c                 &    | j                  d      S )NTdeepr   )r   memos     r   __deepcopy__zTree.__deepcopy__'  s    yydy##r   c                 r    |s t        |       | j                  |       S t        |       j                  |       S r   )r
   r   r   )r   r   s     r   r   z	Tree.copy*  s1    4:dkk400:%%d++r   c                     ddl m} |S )Nr   )ImmutableTree)nltk.tree.immutabler   )r   r   s     r   _frozen_classzTree._frozen_class0  s    5r   c                     | j                         }||j                  |       }nG| j                  d      }|j                  d      D ]  } |||         ||<    |j                  |      }t	        |       |S )NTr   rP   )r   r   r   rc   hash)r   leaf_freezerfrozen_classnewcopyro   s        r   freezezTree.freeze5  sy    ))+"**40GiiTi*G,,X6+GCL9 7"**73GWr   c           
      P   t        |t              rt        |      dk7  rt        d      t	        j
                  d|      rt        d      |\  }}	t	        j                  |      t	        j                  |	      }}
|d|
 | d}|d|
 | d}t	        j                  |
d|d	|d
|d      }dg fg}|j                  |      D ]D  }|j                         }|d   |k(  rft        |      dk(  r't        |d   d         dkD  r| j                  ||d       |dd j                         }| ||      }|j                  |g f       ||	k(  r|t        |      dk(  r;t        |d   d         dk(  r| j                  |||       n| j                  ||d       |j                         \  }}|d   d   j                   | ||             t        |      dk(  r| j                  |||       | ||      }|d   d   j                  |       G t        |      dkD  r| j                  |d|	       nHt        |d   d         dk(  r| j                  |d|       n |d   d   J t        |d   d         dk(  sJ |d   d   d   }|r"|j                  dk(  rt        |      dk(  r|d   }|S )a'  
        Read a bracketed tree string and return the resulting tree.
        Trees are represented as nested brackettings, such as::

          (S (NP (NNP John)) (VP (V runs)))

        :type s: str
        :param s: The string to read

        :type brackets: str (length=2)
        :param brackets: The bracket characters used to mark the
            beginning and end of trees and subtrees.

        :type read_node: function
        :type read_leaf: function
        :param read_node, read_leaf: If specified, these functions
            are applied to the substrings of ``s`` corresponding to
            nodes and leaves (respectively) to obtain the values for
            those nodes and leaves.  They should have the following
            signature:

               read_node(str) -> value

            For example, these functions could be used to process nodes
            and leaves whose values should be some type other than
            string (such as ``FeatStruct``).
            Note that by default, node strings and leaf strings are
            delimited by whitespace and brackets; to override this
            default, use the ``node_pattern`` and ``leaf_pattern``
            arguments.

        :type node_pattern: str
        :type leaf_pattern: str
        :param node_pattern, leaf_pattern: Regular expression patterns
            used to find node and leaf substrings in ``s``.  By
            default, both nodes patterns are defined to match any
            sequence of non-whitespace non-bracket characters.

        :type remove_empty_top_bracketing: bool
        :param remove_empty_top_bracketing: If the resulting tree has
            an empty node label, and is length one, then return its
            single child instead.  This is useful for treebank trees,
            which sometimes contain an extra level of bracketing.

        :return: A tree corresponding to the string representation ``s``.
            If this class method is called using a subclass of Tree,
            then it will return a tree of that type.
        :rtype: Tree
           z"brackets must be a length-2 stringz\szwhitespace brackets not allowedNz[^\sz]+z\s*(z)?|z|()r   r4   end-of-stringrq    )r   r   r:   r	   researchescapecompilefinditergroup_parse_errorlstriprQ   rr   r   )r   sbrackets	read_node	read_leafnode_patternleaf_patternremove_empty_top_bracketingopen_bclose_bopen_patternclose_patterntoken_rert   matchtokenrK   r   r   s                      r   
fromstringzTree.fromstringE  s   x (C(CMQ,>@AA99UH%=>>"')yy'8"))G:Lm"<.rBL"<.rBL::\=,H

 &&q)EKKMEQx6!u:?s58A;'7!';$$Q?ab	((*(%e,EeR[)'!u:?58A;'1,((E6:((E?C"'))+xb	!##Cx$89 u:?$$Qv6(%e,Eb	!##E*3 *8 u:>Q9q!"Q88A;&&&uQx{#q(((Qx{1~ '4;;"+<Ta7Dr   c                    |dk(  rt        |      d}}n |j                         |j                         }}d| j                  ||d|fz  }|j	                  dd      j	                  dd      }|}t        |      |dz   kD  r|d|dz    d	z   }|dkD  rd	||dz
  d z   }d
}|dj                  d|dd|z   z        z  }t        |      )z
        Display a friendly error message when parsing a tree string fails.
        :param s: The string we're parsing.
        :param match: regexp match of the problem token.
        :param expecting: what we expected to see instead.
        r   z0%s.read(): expected %r but got %r
%sat index %d.z            
 	
   Nz...   z
{}"{}"
{}^z                   )r:   ry   r   r   replaceformatrx   )r   r   r   	expectingro   r   msgoffsets           r   r   zTree._parse_error  s     O#QCCALLE
 
 IIdC ((s3q6C"H*C"H%A8#(*%AF%%h3"v+3FGGor   c           	          t        |      t        k(  rYt        |      dkD  rJt        |d         }t        |      dkD  r,t	        ||dd D cg c]  }| j                  |       c}      S |S yyc c}w )z
        :type l: list
        :param l: a tree represented as nested lists

        :return: A tree corresponding to the list representation ``l``.
        :rtype: Tree

        Convert nested lists to a NLTK Tree
        r   r4   N)r
   r   r:   reprr   fromlist)r   lrK   rR   s       r   r   zTree.fromlist  sn     7d?s1vz1JE1vzEQqrU#KUECLL$7U#KLL  *? $Ls   
A-
c                      ddl m}  ||        y)zP
        Open a new window containing a graphical diagram of this tree.
        r   )
draw_treesN)nltk.draw.treer   )r   r   s     r   drawz	Tree.draw  s     	.4r   c                 Z    ddl m} t          || ||      j                  di ||       y)z
        Pretty-print this tree as ASCII or Unicode art.
        For explanation of the arguments, see the documentation for
        `nltk.tree.prettyprinter.TreePrettyPrinter`.
        r   )TreePrettyPrinterfileNr   )nltk.tree.prettyprinterr   printtext)r   sentence	highlightstreamkwargsr   s         r   pretty_printzTree.pretty_print  s-     	>?h	:??I&IPVWr   c                     dj                  d | D              }dj                  t        |       j                  t	        | j
                        |      S )Nz, c              3   2   K   | ]  }t        |        y wr   )r   )r]   cs     r   r`   z Tree.__repr__.<locals>.<genexpr>  s     3dT!Wds   z{}({}, [{}]))joinr   r
   r   r   r   )r   childstrs     r   __repr__zTree.__repr__  sE    993d33$$J
 	
r   c                 :    ddl m}  ||       j                         S )Nr   )	draw_tree)svglingr   
_repr_svg_)r   r   s     r   r   zTree._repr_svg_  s    %))++r   c                 "    | j                         S r   )pformatrD   s    r   __str__zTree.__str__  s    ||~r   c                 \    d|v r	|d   }|d= nd}t         | j                  di ||       y)zH
        Print a string representation of this Tree to 'stream'
        r   Nr   r   )r   r   )r   r   r   s      r   pprintzTree.pprint  s;    
 vH%Fx Fldll$V$62r   c           
      \   | j                  |||      }t        |      |z   |k  r|S t        | j                  t              r|d    | j                   | }n|d    t        | j                         | }| D ]  }t        |t              r(|dd|dz   z  z   |j                  ||dz   |||      z   z  };t        |t              r!|dd|dz   z  z   dj                  |      z   z  }lt        |t              r|s|dd|dz   z  z   d|z  z   z  }|dd|dz   z  z   t        |      z   z  } ||d   z   S )aI  
        :return: A pretty-printed string representation of this tree.
        :rtype: str
        :param margin: The right margin at which to do line-wrapping.
        :type margin: int
        :param indent: The indentation level at which printing
            begins.  This number is used to decide how far to indent
            subsequent lines.
        :type indent: int
        :param nodesep: A string that is used to separate the node
            from the children.  E.g., the default value ``':'`` gives
            trees like ``(S: (NP: I) (VP: (V: saw) (NP: it)))``.
        r   r   r   r   /%sr4   )
_pformat_flatr:   r   r   r   r   r   r   r9   r   )r   marginindentnodesepparensquotesr   rR   s           r   r   zTree.pformat!  sV     w7q6F?V#H dkk3'!9+dkk]7)4A!9+d4;;/0	:AE%&VaZ()mmFFQJPQ
 E5)TC6A:..%@@E3'TC6A:..==TC6A:..e<<  6!9}r   c                     t        j                  d      }| j                  ddd      }dt        j                  |d|      z   S )a  
        Returns a representation of the tree compatible with the
        LaTeX qtree package. This consists of the string ``\Tree``
        followed by the tree represented in bracketed notation.

        For example, the following result was generated from a parse tree of
        the sentence ``The announcement astounded us``::

          \Tree [.I'' [.N'' [.D The ] [.N' [.N announcement ] ] ]
              [.I' [.V'' [.V' [.V astounded ] [.N'' [.N' [.N us ] ] ] ] ] ] ]

        See https://www.ling.upenn.edu/advice/latex.html for the LaTeX
        style file for the qtree package.

        :return: A latex qtree representation of this tree.
        :rtype: str
        z([#\$%&~_\{\}])   r   )z[.z ])r   r   r   z\Tree z\\\1)r   r   r   sub)r   reserved_charsr   s      r   pformat_latex_qtreezTree.pformat_latex_qtreeI  s?    $ $67,,aL,I266.'7CCCr   c                 t   g }| D ]  }t        |t              r#|j                  |j                  |||             6t        |t              r!|j                  dj                  |             gt        |t              r|s|j                  d|z         |j                  t        |              t        | j                  t              r4dj                  |d   | j                  |dj                  |      |d         S dj                  |d   t        | j                        |dj                  |      |d         S )Nr   r   z{}{}{} {}{}r   r   r4   )
r   r   rQ   r   r9   r   r   r   r   r   )r   r   r   r   	childstrsrR   s         r   r   zTree._pformat_flat`  s   	E%&  !4!4Wff!MNE5)  %1E3'  .  e-  dkk3' ''q	#q	  !''q	T[[!#q	 r   r   )rZ   )rightNr   |^)Tr  r  +)FFr  )F)()NNNNF)Nr   N)F   r   r   r  F)8r   
__module____qualname____doc__r   r   r   __ne____gt____le____ge__r)   r,   r/   r2   r8   r>   rB   r   rE   rH   propertyr   rK   rM   rP   rT   rW   rc   rh   rl   ro   rv   r}   r   r   r   classmethodr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r      s   =~$
	F 3FDF>F1F@@::  & %&X 'X )*Y +Y Iy)D*1$642.2(J40 !YH JMT2B6  $,

   $)v vp  <  *X
,

3&PD.r   r   c                     g }| D ]H  }t        |t              r%|j                  t        |j                               8|j                  |       J |S r   )r   r   rQ   r   r   )r   namesrR   s      r   rk   rk   }  sC    EeT"LLU\\23LL	 
 Lr   c                     ddl m} m} d}|j                  |      }t	        d       t	        |       t	        |j                                t	        d       t	        |j                                t	        |d          t	        |d          t	        |j                                t	        |j                                t	        |d          t	        |d          t	        |d          |d   }|j                  d|j                  d	             t	        d
       t	        |       |j                  d      |d<   t	        |       t	                t	        d       |j                          t	        |       t	        d       |j                          t	        |       t	                 | dddgd      }t	        d       t	        |       t	                |j                  |j                               }t	        d       t	        |       t	                t	        d       t	        |j                                t	                t	        d       t	        |j                                t	                |j                  d       t	        |       y)z
    A demonstration showing how Trees and Trees can be
    used.  This demonstration creates a Tree, and loads a
    Tree from the Treebank corpus,
    and shows the results of calling several of their methods.
    r   )ProbabilisticTreer   zA(S (NP (DT the) (NN cat)) (VP (VBD ate) (NP (DT a) (NN cookie))))z#Convert bracketed string into tree:zDisplay tree properties:r4   )r4   r4   )r4   r4   r   z(JJ big)zTree modification:z	(NN cake))r4   r4   r4   zCollapse unary:zChomsky normal form:xyzg      ?)probzProbabilistic Tree:z0Convert tree to bracketed string and back again:zLaTeX output:zProduction output:)test   N)nltkr  r   r   r   r   rK   rW   rP   insertr   r   r   r   rl   rM   )r  r   r   tthe_catpts         r   demor     s    - 	LAA	
/0	!H	!**,	
$%	!'')	!A$K	!A$K	!((*	!((*	!A$K	!D'N	!G* dGNN1dooj12	
	!H-AgJ	!H	G 

	!H	
 !	!H	G 
3c
	5B	
 	"I	G 			$A	
<=	!H	G 
/	!


!"	G 

	!--/	G KK	!Hr   )r
  r   nltk.grammarr   r   nltk.internalsr   r   r   rk   r   __all__r   r   r   <module>r$     s<   
 
 0 %^4 ^BER r   