³ò
3ÒÇIc           @   sL  d  Z  d d k Z d d k Z d d k Z d d k l Z d d k l Z l Z l Z d d k	 l
 Z
 l Z d d k l Z d e f d „  ƒ  YZ d	 e f d
 „  ƒ  YZ e i d ƒ Z d d d d „ Z d e f d „  ƒ  YZ d d d d „ Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z d „  Z e d j o e ƒ  n d S(   sU   
Module for reading, writing and manipulating 
Toolbox databases and settings files.
iÿÿÿÿN(   t   StringIO(   t   TreeBuildert   Elementt
   SubElement(   t   PathPointert   ZipFilePathPointer(   t   datat   StandardFormatc           B   sY   e  Z d  Z e e d „ Z d „  Z d „  Z d „  Z e e e d e d „ Z	 d „  Z
 RS(   sT   
    Class for reading and processing standard format marker files and strings.
    c         C   s+   | |  _  | d  j	 o |  i | ƒ n d  S(   N(   t	   _encodingt   Nonet   open(   t   selft   filenamet   encoding(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   __init__   s    	c         C   sH   t  | t ƒ o | i |  i ƒ |  _ n t i | d |  i ƒ |  _ d S(   s¶   Open a standard format marker file for sequential reading. 
        
        @param sfm_file: name of the standard format marker input file
        @type sfm_file: C{string}
        t   rUN(   t
   isinstanceR   R
   R   t   _filet   codecs(   R   t   sfm_file(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR
       s    c         C   s   t  | ƒ |  _ d S(   s³   Open a standard format marker string for sequential reading. 
        
        @param s: string to parse as a standard format marker input file
        @type s: C{string}
        N(   R    R   (   R   t   s(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   open_string-   s    c         c   s)  d } d } t  i | d ƒ } t  i | d ƒ } t |  i ƒ } | i ƒ  } t  i | | ƒ } | i ƒ  \ } }	 |	 g }
 d |  _ x| | D]t } |  i d 7_ t  i | | ƒ } | i ƒ  \ } }	 | o' | | i |
 ƒ f V| } |	 g }
 qŠ |
 i	 |	 ƒ qŠ W|  i d 7_ | | i |
 ƒ f Vd S(   sd  Return an iterator for the fields in the standard format marker
        file.
        
        @return: an iterator that returns the next field in a (marker, value) 
            tuple. Linebreaks and trailing white space are preserved except 
            for the final newline in each field.
        @rtype: iterator over C{(marker, value)} tuples
        s   
s   ^%s(?:\\(\S+)\s*)?(.*)$u   ï»¿?t    i    i   N(
   t   ret   compilet   iterR   t   nextt   matcht   groupst   line_numt   joint   append(   R   t   join_stringt   line_regexpt   first_line_patt   line_patt	   file_itert   linet   mobjt   mkrt
   line_valuet   value_linest   line_mkr(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt
   raw_fields5   s,    			 t   strictc   	      c   sõ   | d j o | d j	 o t d ‚ n t i d ƒ } x¸ |  i ƒ  D]ª \ } } | oX | d j	 o# | | j o | i d | ƒ } n | i | | ƒ } | i | | ƒ } n | o | i d | ƒ } n | o | i ƒ  } n | | f VqC Wd S(   sM  Return an iterator for the fields in the standard format marker file.
        
        @param strip: strip trailing whitespace from the last line of each field
        @type strip: C{boolean}
        @param unwrap: Convert newlines in a field to spaces.
        @type unwrap: C{boolean}
        @param encoding: Name of an encoding to use. If it is specified then 
            the C{fields} method returns unicode strings rather than non 
            unicode strings.
        @type encoding: C{string} or C{None}
        @param errors: Error handling scheme for codec. Same as the C{decode} 
        inbuilt string method.
        @type errors: C{string}
        @param unicode_fields: Set of marker names whose values are UTF-8 encoded.
            Ignored if encoding is None. If the whole file is UTF-8 encoded set 
            C{encoding='utf8'} and leave C{unicode_fields} with its default
            value of None.
        @type unicode_fields: set or dictionary (actually any sequence that 
            supports the 'in' operator).
        @return: an iterator that returns the next field in a C{(marker, value)} 
            tuple. C{marker} and C{value} are unicode strings if an C{encoding} was specified in the 
            C{fields} method. Otherwise they are nonunicode strings.
        @rtype: iterator over C{(marker, value)} tuples
        s'   unicode_fields is set but not encoding.s   \n+t   utf8t    N(   R	   t
   ValueErrorR   R   R+   t   decodet   subt   rstrip(	   R   t   stript   unwrapR   t   errorst   unicode_fieldst
   unwrap_patR'   t   val(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   fieldsW   s     c         C   s1   |  i  i ƒ  y
 |  ` Wn t j
 o n Xd S(   s@   Close a previously opened standard format marker file or string.N(   R   t   closeR   t   AttributeError(   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR:   €   s
    
(   t   __name__t
   __module__t   __doc__R	   R   R
   R   R+   t   TrueR9   R:   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR      s   			")t   ToolboxDatac           B   s;   e  Z e d  „ Z e d „ Z d „  Z e d d d „ Z RS(   c         K   s/   | o |  i  d | |  Sn |  i |   Sd  S(   Nt   grammar(   t   _chunk_parset   _record_parse(   R   RA   t   kwargs(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   parse‰   s    c         K   s1  t  ƒ  } | i d h  ƒ | i d h  ƒ t } xÃ |  i |   D]² \ } } | t j o# | o | d d j o
 | } n | | j o? | o | i d ƒ n | i d ƒ t } | i d h  ƒ n | i | h  ƒ | i | ƒ | i | ƒ q? W| o | i d ƒ n | i d ƒ | i d ƒ | i ƒ  S(   sà  
        Returns an element tree structure corresponding to a toolbox data file with
        all markers at the same level.
       
        Thus the following Toolbox database::
            \_sh v3.0  400  Rotokas Dictionary
            \_DateStampHasFourDigitYear
            
            \lx kaa
            \ps V.A
            \ge gag
            \gp nek i pas
            
            \lx kaa
            \ps V.B
            \ge strangle
            \gp pasim nek

        after parsing will end up with the same structure (ignoring the extra 
        whitespace) as the following XML fragment after being parsed by 
        ElementTree::
            <toolbox_data>
                <header>
                    <_sh>v3.0  400  Rotokas Dictionary</_sh>
                    <_DateStampHasFourDigitYear/>
                </header>
    
                <record>
                    <lx>kaa</lx>
                    <ps>V.A</ps>
                    <ge>gag</ge>
                    <gp>nek i pas</gp>
                </record>
                
                <record>
                    <lx>kaa</lx>
                    <ps>V.B</ps>
                    <ge>strangle</ge>
                    <gp>pasim nek</gp>
                </record>
            </toolbox_data>

        @param key: Name of key marker at the start of each record. If set to 
        None (the default value) the first marker that doesn't begin with an 
        underscore is assumed to be the key.
        @type key: C{string}
        @param kwargs: Keyword arguments passed to L{StandardFormat.fields()}
        @type kwargs: keyword arguments dictionary
        @rtype:   C{ElementTree._ElementInterface}
        @return:  contents of toolbox data divided into header and records
        t   toolbox_datat   headeri    t   _t   record(	   R   t   startt   FalseR9   R	   t   endR?   R   R:   (   R   t   keyRD   t   buildert
   in_recordsR'   t   value(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRC      s,    4	 &
c         C   s‚   d d k  l } t | i ƒ } x\ | D]T } t | | ƒ o | i |  i | ƒ ƒ q& | \ } } t | | ƒ } | | _ q& W| S(   Niÿÿÿÿ(   t   Tree(	   t
   nltk.parseRQ   R   t   nodeR   R   t   _tree2etreeR   t   text(   R   t   parentRQ   t   roott   childRU   t   tagt   e(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRT   Û   s     RI   i    c      	   K   sÜ   d d k  l } d d k l } | i | d | d | ƒ} |  i |   } t d ƒ }	 | i d ƒ }
 |	 i |
 ƒ xc | i	 d ƒ D]R } | i g  } | D] } | | i
 | i f q™ ~ ƒ } |	 i |  i | ƒ ƒ q‚ W|	 S(	   sä  
        Returns an element tree structure corresponding to a toolbox data file
        parsed according to the chunk grammar.
        
        @type grammar: C{string}
        @param grammar: Contains the chunking rules used to parse the 
        database.  See L{chunk.RegExp} for documentation.
        @type top_node: C{string}
        @param top_node: The node value that should be used for the
            top node of the chunk structure.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            C{1} will generate normal tracing output; and C{2} or
            higher will generate verbose tracing output.
        @type kwargs: C{dictionary}
        @param kwargs: Keyword arguments passed to L{toolbox.StandardFormat.fields()}
        @rtype:   C{ElementTree._ElementInterface}
        @return:  Contents of toolbox data parsed according to the rules in grammar
        iÿÿÿÿ(   t   chunk(   RQ   t   top_nodet   traceRF   RG   RI   (   t   nltkR[   RR   RQ   t   RegexpParserRE   R   t   findR   t   findallRU   RY   RT   (   R   RA   R\   R]   RD   R[   RQ   t   cpt   dbt   tb_etreeRG   RI   t   _[1]t   elemt   parsed(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRB   è   s     6(   R<   R=   R	   RE   RC   RT   RB   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR@   ˆ   s   L	s   \SR,   c         C   s¬  |  i  d j o# t d ƒ } | i |  ƒ | }  n |  i  d j o t d ‚ n | t j o | t j	 o t d ‚ n g  } x|  D]} | i d ƒ xý | D]õ } | i  } | i }	 | t j	 o‹ | t j	 o | | j o
 d }
 n | }
 t i t |	 ƒ o' | i d | |	 f i	 |
 | ƒ ƒ q“| i d | |	 f i	 |
 | ƒ ƒ qž t i t |	 ƒ o | i d	 | |	 f ƒ qž | i d
 | |	 f ƒ qž Wq„ Wd i
 | d ƒ S(   sš  Return a string with a standard format representation of the toolbox
    data in tree (tree can be a toolbox database or a single record).
    
    @param tree: flat representation of toolbox data (whole database or single record)
    @type tree: C{ElementTree._ElementInterface}
    @param encoding: Name of an encoding to use.
    @type encoding: C{string}
    @param errors: Error handling scheme for codec. Same as the C{encode} 
        inbuilt string method.
    @type errors: C{string}
    @param unicode_fields:
    @type unicode_fields: C{dictionary} or C{set} of field names
    @rtype:   C{string}
    @return:  C{string} using standard format markup
    RI   RF   s$   not a toolbox_data element structures?   if encoding is not specified then neither should unicode_fieldss   
R-   u   \%s %s
u   \%s%s
s   \%s %s
s   \%s%s
R   i   (   RY   R   R   R/   R	   RU   R   t   searcht	   _is_valuet   encodeR   (   t   treeR   R5   R6   RW   t   lt   rect   fieldR'   RP   t   cur_encoding(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   to_sfm_string  s8    

  		
''t   ToolboxSettingsc           B   s&   e  Z d  Z d „  Z e d d „ Z RS(   s0   This class is the base class for settings files.c         C   s   t  t |  ƒ i ƒ  d  S(   N(   t   superRq   R   (   R   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR   ?  s    R,   c         K   sà   t  ƒ  } xÊ |  i d | d | |  D]­ \ } } | d } | d j o | d } n t } | d j o! | i | h  ƒ | i | ƒ q% | d j o | i | ƒ q% | i | h  ƒ | i | ƒ | i | ƒ q% W| i ƒ  S(   s  Parses a settings file using ElementTree.
        
        @param encoding: encoding used by settings file
        @type  encoding: C{string}        
        @param errors: Error handling scheme for codec. Same as C{.decode} inbuilt method.
        @type errors: C{string}
        @param kwargs: Keyword arguments passed to L{StandardFormat.fields()}
        @type kwargs: keyword arguments dictionary
        @rtype:   C{ElementTree._ElementInterface}
        @return:  contents of toolbox settings file with a nested structure
        R   R5   i    t   +t   -i   (   Rs   Rt   (   R   R9   R	   RJ   R   RL   R:   (   R   R   R5   RD   RN   R'   RP   t   block(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRE   B  s     	 
(   R<   R=   R>   R   R	   RE   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRq   <  s   	c      	   C   s;   t  ƒ  } t |  i ƒ  | d | d | d | ƒd i | ƒ S(   NR   R5   R6   R   (   t   listt   _to_settings_stringt   getrootR   (   Rk   R   R5   R6   Rl   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   to_settings_stringc  s    	%c         K   sÅ   |  i  } |  i } t |  ƒ d j o7 | o | i d | | f ƒ qÁ | i d | ƒ nf | o | i d | | f ƒ n | i d | ƒ x |  D] } t | | |  q– W| i d | ƒ d  S(   Ni    s   \%s %s
s   \%s
s   \+%s %s
s   \+%s
s   \-%s
(   RY   RU   t   lenR   Rw   (   RS   Rl   RD   RY   RU   t   n(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyRw   i  s    		 c         C   s]   t  ƒ  } xF |  D]> } t | ƒ | i p t | ƒ d j o | i | ƒ q q W| |  (d S(   s¹   Remove all elements and subelements with no text and no child elements.
    
    @param elem: toolbox data in an elementtree structure
    @type elem: ElementTree._ElementInterface
    i    N(   Rv   t   remove_blanksRU   Rz   R   (   Rf   t   outRX   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR|   |  s    	 
c         C   sl   xG | i  |  i g  ƒ D]0 } |  i | ƒ d j o t i |  | ƒ q q Wx |  D] } t | | ƒ qQ Wd S(   s0  Add blank elements and subelements specified in default_fields.
    
    @param elem: toolbox data in an elementtree structure
    @type elem: ElementTree._ElementInterface
    @param default_fields: fields to add to each type of element and subelement
    @type default_fields: dictionary of tuples
    N(   t   getRY   R`   R	   t   ETR   t   add_default_fields(   Rf   t   default_fieldsRn   RX   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR€   ‰  s      c         C   so   t  ƒ  } xR | i ƒ  D]D \ } } t  ƒ  | | <} x$ t | ƒ D] \ } } | | | <q@ Wq Wt |  | ƒ d S(   s5  Sort the elements and subelements in order specified in field_orders.
    
    @param elem: toolbox data in an elementtree structure
    @type elem: ElementTree._ElementInterface
    @param field_orders: order of fields for each type of element and subelement
    @type field_orders: dictionary of tuples
    N(   t   dictt   itemst	   enumeratet   _sort_fields(   Rf   t   field_orderst   order_dictsRn   t   ordert	   order_keyt   it   subfield(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   sort_fields—  s    	  c   	      C   sÔ   y | |  i  } Wn t j
 o n| Xg  } t |  ƒ D]. \ } } | | i | i  d ƒ | f | f q8 ~ } | i ƒ  g  } | D] \ } } | | q„ ~ |  (x, |  D]$ } t | ƒ o t | | ƒ q¨ q¨ Wd S(   s   sort the children of elemg    eÍÍAN(   RY   t   KeyErrorR„   R~   t   sortRz   R…   (	   Rf   t   orders_dictsRˆ   Re   RŠ   RX   t   tmpt   _[2]RM   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR…   ¦  s    H
( c   	      C   sO  y | |  i  } | |  i  } WnE t j
 o9 x|  D]' } t | ƒ o t | | | ƒ q6 q6 Wnç Xd } xÜ |  D]Ô } | i  } | d j	 oY | i  | j oI | | j o8 | d j	 o+ | i ƒ  d } | i p d d | _ q n9 | | j o+ | i ƒ  d } | i p d d | _ n t | ƒ o t | | | ƒ n | } qs Wd S(   s9  Add blank lines before all elements and subelements specified in blank_before.
    
    @param elem: toolbox data in an elementtree structure
    @type elem: ElementTree._ElementInterface
    @param blank_before: elements and subelements to add blank lines before
    @type blank_before: dictionary of tuples
    iÿÿÿÿR   s   
N(   RY   R   Rz   t   add_blank_linesR	   t   getiteratorRU   (	   Rk   t   blanks_beforet   blanks_betweent   beforet   betweenRf   t	   last_elemRY   RZ   (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyR’   ´  s,      	c          C   s?  d d k  l }  t i d ƒ } t | ƒ i ƒ  } d GH| d d i GH| d d i GHd GHx/ |  | i d ƒ d	 ƒ D] } | i G| i GHqt Wd
 GHx( |  | i d ƒ d	 ƒ D] } | i GHq« Wd d k	 l
 } t ƒ  } t i d ƒ } | i | ƒ | i d t d d ƒ } | i d ƒ i GH| | ƒ } t | ƒ i d ƒ GHd  S(   Niÿÿÿÿ(   t   islices   corpora/toolbox/rotokas.dics   first field in fourth record:i   i    s   
fields in sequential order:RI   i
   s   
lx fields:s	   record/lx(   t   ElementTrees    corpora/toolbox/MDF/MDF_AltH.typR4   R   t   cp1252s$   expset/expMDF/rtfPageSetup/paperSizeR-   (   t	   itertoolsR™   R   R`   R@   RE   RY   RU   Ra   t   nltk.etree.ElementTreeRš   Rq   R
   RK   Ry   Rj   (   R™   t	   file_patht   lexiconRn   Rš   t   settingsRk   t   settings_tree(    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pyt   demoÓ  s,      	t   __main__(   R>   t   osR   R   R    R   R   R   R   t	   nltk.dataR   R   R^   R   t   objectR   R@   R   Ri   R	   Rp   Rq   Ry   Rw   R|   R€   RŒ   R…   R’   R¢   R<   (    (    (    s"   /p/zhu/06/nlp/nltk/nltk/toolbox.pys   <module>   s(   $q‚0'							