JL iEdZddlZddlZddlmZddlmZmZmZm Z ddl m Z m Z GddZ Gdd e Zejd Zdd ZGd d e ZddZdZdZdZdZdZdZdZedk(reyy)zT Module for reading, writing and manipulating Toolbox databases and settings files. N)StringIO)Element ElementTree SubElement TreeBuilder) PathPointerfindcBeZdZdZd dZdZdZdZ d dZdZ y) StandardFormatzT Class for reading and processing standard format marker files and strings. Nc:||_||j|yyN) _encodingopen)selffilenameencodings R/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/toolbox.py__init__zStandardFormat.__init__s !   IIh  ct|tr!|j|j|_yt j|d|j|_y)z Open a standard format marker file for sequential reading. :param sfm_file: name of the standard format marker input file :type sfm_file: str rN) isinstancerrr_filecodecs)rsfm_files rrzStandardFormat.opens: h ,!t~~6DJXsDNNCDJrc$t||_y)z Open a standard format marker string for sequential reading. :param s: string to parse as a standard format marker input file :type s: str N)rr)rss r open_stringzStandardFormat.open_string+sa[ rc#tKd}d}tj|dz}tj|dz}t|j} t |}tj ||}|j\}} | g} d|_|D]n}|xjdz c_tj ||}|j\} } | r||j| f| }| g} ^| j| p|xjdz c_||j| fy#t $rYywxYww)z 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: iter(tuple(str, str))  z^%s(?:\\(\S+)\s*)?(.*)$u (?:)?Nr) recompileiterrnext StopIterationmatchgroupsline_numjoinappend) r join_string line_regexpfirst_line_patline_pat file_iterlinemobjmkr line_value value_linesline_mkrs r raw_fieldszStandardFormat.raw_fields4s/ 0 K2E$EF::kB./$   ?Dxx-++-Z!l   /D MMQ M88Hd+D#';;= HjK,,[9::)l "":. /  K$$[122%   s+A D8 D)CD8) D52D84D55D8c#K| | tdtjd}|jD]1\}}|r|j d|}|r|j }||f3yw)a Return an iterator that returns the next field in a ``(marker, value)`` tuple, where ``marker`` and ``value`` are unicode strings if an ``encoding`` was specified in the ``fields()`` method. Otherwise they are non-unicode strings. :param strip: strip trailing whitespace from the last line of each field :type strip: bool :param unwrap: Convert newlines in a field to spaces. :type unwrap: bool :param encoding: Name of an encoding to use. If it is specified then the ``fields()`` method returns unicode strings rather than non unicode strings. :type encoding: str or None :param errors: Error handling scheme for codec. Same as the ``decode()`` builtin string method. :type errors: str :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 ``encoding='utf8'`` and leave ``unicode_fields`` with its default value of None. :type unicode_fields: sequence :rtype: iter(tuple(str, str)) Nz'unicode_fields is set but not encoding.z\n+ ) ValueErrorr#r$r8subrstrip) rstripunwraprerrorsunicode_fields unwrap_patr4vals rfieldszStandardFormat.fields[sr>   :FG GZZ' ) HC nnS#.jjl*   sA*A,c\|jj |`y#t$rYywxYw)z@Close a previously opened standard format marker file or string.N)rcloser*AttributeError)rs rrFzStandardFormat.closes.      s  ++)NN)TTNstrictN) __name__ __module__ __qualname____doc__rrrr8rDrFrrr r s9 D!%3R 'Rrr c*eZdZddZddZdZddZy) ToolboxDataNc R|r|jdd|i|S|jdi|S)NgrammarrM) _chunk_parse _record_parse)rrQkwargss rparsezToolboxData.parses6 $4$$?W?? ?%4%%// /rc "t}|jdi|jdid}|jdi|D]\}}| |s |ddk7r|}||k(r9|r|jdn|jdd}|jdi|j|i|j ||j||r|jdn|jd|jd|j S) a 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::
<_sh>v3.0 400 Rotokas Dictionary <_DateStampHasFourDigitYear/>
kaa V.A gag nek i pas kaa V.B strangle pasim nek
: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: str :param kwargs: Keyword arguments passed to ``StandardFormat.fields()`` :type kwargs: dict :rtype: ElementTree._ElementInterface :return: contents of toolbox data divided into header and records toolbox_dataheaderFr_recordTrM)rstartrDenddatarF)rkeyrTbuilder in_recordsr4values rrSzToolboxData._record_parsesh- nb) h# %$++// JC{:#a&C-czKK)KK)!%J h+ MM#r " LL  KK    KK ! KK ! N#}}rcddlm}t|j}|D]G}t ||r!|j |j |0|\}}t||}||_I|S)NrTree) nltk.treerdrlabelrr, _tree2etreertext)rparentrdrootchildrhtages rrgzToolboxData._tree2etreesh"v||~& E%& D,,U34! ctS)   rc ddlm}ddlm}|j |||}|j di|}t d} |jd} | j| |jdD]W} |j | D cgc]} | j| jfc} } | j|j| Y| Scc} w) aw Returns an element tree structure corresponding to a toolbox data file parsed according to the chunk grammar. :type grammar: str :param grammar: Contains the chunking rules used to parse the database. See ``chunk.RegExp`` for documentation. :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. :type kwargs: dict :param kwargs: Keyword arguments passed to ``toolbox.StandardFormat.fields()`` :rtype: ElementTree._ElementInterface r)chunkrc) root_labeltracerWrXrZrM) nltkrorerd RegexpParserrUrr r,findallrhrlrg)rrQrprqrTrordcpdbtb_etreerXrZelemparseds rrRzToolboxData._chunk_parses( "   Je  L TZZ !& !>*"jj* 6FXXH 4884HIF OOD,,V4 5 6IsC r )NrZr)rIrJrKrUrSrgrRrMrrrOrOs0 JX rrOz\Sc |jdk(rtd}|j||}|jdk7r td| | tdg}|D]}|jd|D]}|j}|j} |v|||vrd} n|} t j t| r)|jd|d | dj| |k|jd|| dj| |t j t| r|jd|d | d|jd|| dd j|d dS) a@ 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: ElementTree._ElementInterface :param encoding: Name of an encoding to use. :type encoding: str :param errors: Error handling scheme for codec. Same as the ``encode()`` builtin string method. :type errors: str :param unicode_fields: :type unicode_fields: dict(str) or set(str) :rtype: str rZrWz$not a toolbox_data element structureNz?if encoding is not specified then neither should unicode_fieldsr utf8\r:r!r") rlrr,r;rhr#search _is_valueencoder+) treerr@rArjlrecfieldr4ra cur_encodings r to_sfm_stringrsq  xx8~& D xx>!?@@N6 M   A2  2E))CJJE#!-#2G#)L#+L99Y.HH3%qr2::<PQHH3%wb199,OP99Y.HHr#awb12HHr#ugR01! 22& 771QR5>rc*eZdZdZfdZddZxZS)ToolboxSettingsz0This class is the base class for settings files.c"t|yr )superr)r __class__s rrzToolboxSettings.__init__Gs rc zt}|jd||d|D]\}}|d}|dvr|dd}nd}|dk(r$|j|i|j|@|dk(r|j |W|j|i|j||j ||j S) a Return the contents of toolbox settings file with a nested structure. :param encoding: encoding used by settings file :type encoding: str :param errors: Error handling scheme for codec. Same as ``decode()`` builtin method. :type errors: str :param kwargs: Keyword arguments passed to ``StandardFormat.fields()`` :type kwargs: dict :rtype: ElementTree._ElementInterface )rr@r)+-r"NrrrM)rrDr[r]r\rF)rrr@rTr_r4rablocks rrUzToolboxSettings.parseJs-%$++QxQ&Q !JCFE "!"g| c2& U## C  c2& U# C # !$}}r)NrH)rIrJrKrLrrU __classcell__)rs@rrrDs:rrctt}t|j||||dj|S)N)rr@rAr!)list_to_settings_stringgetrootr+)rrr@rArs rto_settings_stringrls6 A  %  771:rc ^|j}|j}t|dk(r0|r|jd|d|dy|jd|zy|r|jd|d|dn|jd|z|D]}t ||fi||jd|zy) Nrr|r:r z\%s z\+z\+%s z\-%s )rlrhlenr,r)noderrTrlrhns rrrys ((C 99D 4yA~  HHr#avR( )  HHX^ $   HHs3%qb) * HHY_ % 0A 1 / / 0 S! rct}|D]9}t||jst|dkDs)|j |;||ddy)z Remove all elements and subelements with no text and no child elements. :param elem: toolbox data in an elementtree structure :type elem: ElementTree._ElementInterface rN)r remove_blanksrhrr,)rxoutrks rrrsJ &Ce ::Ua JJu DGrc|j|jgD] }|j|t||"|D]}t ||y)a( 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: dict(tuple) N)getrlr radd_default_fields)rxdefault_fieldsrrks rrrsX ##DHHb1$ 99U  # tU #$25.12rct}|jD],\}}tx||<}t|D] \}}|||< .t||y)a- 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: dict(tuple) N)dictitems enumerate _sort_fields)rx field_orders order_dictsrorder order_keyisubfields r sort_fieldsrsf&K$**,$ u)-/ EY$U+ $KAx"#Ih  $${#rc ||jtfdt|D}|Dcgc]\}}| c}}|dd|D]}t |st ||ycc}}w#t$rY1wxYw)zsort the children of elemc3dK|]'\}}j|jd|f|f)yw)geAN)rrl).0rrkrs r z_sort_fields..s3 8@5eii 3' +U 3 s-0N)rlsortedrKeyErrorrr)rx orders_dictstmpr^rkrs @rrrs0TXX& DMdO  ,//ZS%5/Q. u:  -.0    sA- A'- A98A9c ||j}||j}d}|D]}|j}|A|j|k7r2||vr]|[|jd}|jxsddz|_n/||vr+|jd}|jxsddz|_t|r t ||||}y#t $r#|D]}t|st |||YywxYw)a1 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: dict(tuple) Nr!r )rl getiteratorrhradd_blank_linesr) r blanks_beforeblanks_betweenbeforebetween last_elemrxrlrms rrrstxx( *   D((C$#)=&=Y%:!--/3Affld2AF'>!--/3Affld2AF4ym^DI  E ED4ym^D EEsCC.C.-C.cddlm}td}t|j }t dt |ddj t |ddjt d||jddD]"}t |j |j$t d ||jd dD]}t |jt}td }|j||j d d }t |jdjt|}t t|jdy)Nr)islicezcorpora/toolbox/rotokas.diczfirst field in fourth record:z fields in sequential order:rZ z lx fields:z record/lxz corpora/toolbox/MDF/MDF_AltH.typFcp1252)r?rz$expset/expMDF/rtfPageSetup/paperSizer{) itertoolsrr rOrUprintrlrhrtrrrrr)r file_pathlexiconrsettingsr settings_trees rdemors7 23I)$**,G )* '!*Q-   '!*Q-   )* X.3% eii$% . 4b9 ejj H78I MM) >>> :D $)): ; @ @A%M ] + 2 26 :;r__main__)NrHN)rLrr#iorxml.etree.ElementTreerrrr nltk.datarr r rOr$r~rrrrrrrrrrrIrMrrrs  OO'uup.D BJJu  /d%n%P  (  2 $" . B<: zFr