JL iEbddlmZddlmZddlmZmZGddeZdZe dk(reyy) )reduce)ParserI)ProbabilisticTreeTreecPeZdZdZd dZdZddZdZdZdZ dZ d Z d Z d Z y ) ViterbiParsera A bottom-up ``PCFG`` parser that uses dynamic programming to find the single most likely parse for a text. The ``ViterbiParser`` parser parses texts by filling in a "most likely constituent table". This table records the most probable tree representation for any given span and node value. In particular, it has an entry for every start index, end index, and node value, recording the most likely subtree that spans from the start index to the end index, and has the given node value. The ``ViterbiParser`` parser fills in this table incrementally. It starts by filling in all entries for constituents that span one element of text (i.e., entries where the end index is one greater than the start index). After it has filled in all table entries for constituents that span one element of text, it fills in the entries for constitutants that span two elements of text. It continues filling in the entries for constituents spanning larger and larger portions of the text, until the entire table has been filled. Finally, it returns the table entry for a constituent spanning the entire text, whose node value is the grammar's start symbol. In order to find the most likely constituent with a given span and node value, the ``ViterbiParser`` parser considers all productions that could produce that node value. For each production, it finds all children that collectively cover the span and have the node values specified by the production's right hand side. If the probability of the tree formed by applying the production to the children is greater than the probability of the current entry in the table, then the table is updated with this new tree. A pseudo-code description of the algorithm used by ``ViterbiParser`` is: | Create an empty most likely constituent table, *MLC*. | For width in 1...len(text): | For start in 1...len(text)-width: | For prod in grammar.productions: | For each sequence of subtrees [t[1], t[2], ..., t[n]] in MLC, | where t[i].label()==prod.rhs[i], | and the sequence covers [start:start+width]: | old_p = MLC[start, start+width, prod.lhs] | new_p = P(t[1])P(t[1])...P(t[n])P(prod) | if new_p > old_p: | new_tree = Tree(prod.lhs, t[1], t[2], ..., t[n]) | MLC[start, start+width, prod.lhs] = new_tree | Return MLC[0, len(text), start_symbol] :type _grammar: PCFG :ivar _grammar: The grammar used to parse sentences. :type _trace: int :ivar _trace: The level of tracing output that should be generated when parsing a text. c ||_||_y)a Create a new ``ViterbiParser`` parser, that uses ``grammar`` to parse texts. :type grammar: PCFG :param grammar: The grammar used to parse texts. :type trace: int :param trace: The level of tracing that should be used when parsing a text. ``0`` will generate no tracing output; and higher numbers will produce more verbose tracing output. N)_grammar_trace)selfgrammartraces X/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/parse/viterbi.py__init__zViterbiParser.__init__Ks   c|jSNr r s rr zViterbiParser.grammar[s }}rc||_y)aP Set the level of tracing output that should be generated when parsing a text. :type trace: int :param trace: The trace level. A trace level of ``0`` will generate no tracing output; and higher trace levels will produce more verbose tracing output. :rtype: None N)r )r rs rrzViterbiParser.trace^s  rc#Kt|}|jj|i}|jr t dt t |D]>}||}||||dz|f<|jdkDs#|j||t |@t dt |dzD]X}|jrt dd|zzt t ||z dzD]}|||zf}|j|||Z|jdt ||jjf}||yyw)Nz;Inserting tokens into the most likely constituents table...z$Finding the most likely constituentsz spanning %d text elements...r) listr check_coverager printrangelen_trace_lexical_insertion_add_constituents_spanninggetstart) r tokens constituentsindextokenlengthr!spantrees rparsezViterbiParser.parseksVf $$V,  ;; T U3v;' IE5ME49L 50 1{{Q--eUCKH  IAs6{Q/ LF{{:5>?s6{V3a78 Luv~.//lFK L  LCK1D1D1F GH  J s A6E9CEc d}|rid}|j||}|D]J\}}|Dcgc]}t|ts|} }td| |j } |j j } t| || } |j|d|d|j f}|jdkDrb||| k7r[|!|j | j krtdd n td d |j|| |t||#|j | j ks-| ||d|d|j f<d}M|rhyycc}w) a* Find any constituents that might cover ``span``, and add them to the most likely constituents table. :rtype: None :type span: tuple(int, int) :param span: The section of the text for which we are trying to find possible constituents. The span is specified as a pair of integers, where the first integer is the index of the first token that should be included in the constituent; and the second integer is the index of the first token that should not be included in the constituent. I.e., the constituent should cover ``text[span[0]:span[1]]``, where ``text`` is the text that we are parsing. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree) :param constituents: The most likely constituents table. This table records the most probable tree representation for any given span and node value. In particular, ``constituents(s,e,nv)`` is the most likely ``ProbabilisticTree`` that covers ``text[s:e]`` and has a node value ``nv.symbol()``, where ``text`` is the text that we are parsing. When ``_add_constituents_spanning`` is called, ``constituents`` should contain all possible constituents that are shorter than ``span``. :type tokens: list of tokens :param tokens: The text we are parsing. This is only used for trace output. TFc(||jzSrprob)prts rz:ViterbiParser._add_constituents_spanning..saffhrr,rrNz Insert: endz Discard:) _find_instantiations isinstancerrr-lhssymbolrr r r_trace_productionr) r r'r#r"changedinstantiations productionchildrencsubtreespnoder(s rrz(ViterbiParser._add_constituents_spannings[HG"66t\JN )7 #$ H'/G!:a3FAGG6*//BST!~~'..0(xa@!$$d1gtAw 8H%IJ;;?yAI9499;(>!,C8!,C8..z1dCKP9499; 6GKLa$q':>>3C!CD"G% #Hs E0E0cg}|jjD]=}|j|j||}|D]}|j ||f?|S)a  :return: a list of the production instantiations that cover a given span of the text. A "production instantiation" is a tuple containing a production and a list of children, where the production's right hand side matches the list of children; and the children cover ``span``. :rtype: list of ``pair`` of ``Production``, (list of (``ProbabilisticTree`` or token. :type span: tuple(int, int) :param span: The section of the text for which we are trying to find production instantiations. The span is specified as a pair of integers, where the first integer is the index of the first token that should be covered by the production instantiation; and the second integer is the index of the first token that should not be covered by the production instantiation. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree) :param constituents: The most likely constituents table. This table records the most probable tree representation for any given span and node value. See the module documentation for more information. )r productions _match_rhsrhsappend)r r'r#rvr; childlists childlists rr4z"ViterbiParser._find_instantiationsse0--335 3J)94NJ' 3  :y12 3 3  rc |\}}||k\r|dk(rggS||k\s|dk(rgSg}t||dzD]K}|j|||df}||j|dd||f|} || D cgc]} |g| z c} z }M|Scc} w)al :return: a set of all the lists of children that cover ``span`` and that match ``rhs``. :rtype: list(list(ProbabilisticTree or token) :type rhs: list(Nonterminal or any) :param rhs: The list specifying what kinds of children need to cover ``span``. Each nonterminal in ``rhs`` specifies that the corresponding child should be a tree whose node value is that nonterminal's symbol. Each terminal in ``rhs`` specifies that the corresponding child should be a token whose type is that terminal. :type span: tuple(int, int) :param span: The section of the text for which we are trying to find child lists. The span is specified as a pair of integers, where the first integer is the index of the first token that should be covered by the child list; and the second integer is the index of the first token that should not be covered by the child list. :type constituents: dict(tuple(int,int,Nonterminal) -> ProbabilisticToken or ProbabilisticTree) :param constituents: The most likely constituents table. This table records the most probable tree representation for any given span and node value. See the module documentation for more information. rrN)rr rC) r rDr'r#r!r3rGsplitlrightsrs rrCzViterbiParser._match_rhss4  Crrs r__repr__zViterbiParser.__repr__@s'$--77rN)r)rT)__name__ __module__ __qualname____doc__rr rr)rr4rCr8rrYrJrrrrs?5n  'RB#H@*X. 8rrcNddl}ddl}ddlm}ddlm}ddlm}|jd}|jd}d|fd |fg}ttt|D]:}t|d zd d ||dtd ||d zt<tdd t|fzd t|jjjd z } || \} } | j!} || } i}td| d| d| | j#d|j}| j%| }|j|z }|rt'd|dt|z nd}t|}|D]}d ||j)<ttdtdtd|||fz|j+}|rt'd|dt|z }nd}tdtddt||fzttdd|jjjj-j/drdd lm}td!||ttd"d|jjjj-j/dr|D] }t|yy#tdYyxYw)#z A demonstration of the probabilistic parsers. The user is prompted to select which demo to run, and how many parses should be found; and then each parser is run on the same demo, and a summary of the results are displayed. rN)tokenize)PCFG)ra7 S -> NP VP [1.0] NP -> Det N [0.5] | NP PP [0.25] | 'John' [0.1] | 'I' [0.15] Det -> 'the' [0.8] | 'my' [0.2] N -> 'man' [0.5] | 'telescope' [0.5] VP -> VP PP [0.1] | V NP [0.7] | V [0.2] V -> 'ate' [0.35] | 'saw' [0.65] PP -> P NP [1.0] P -> 'with' [0.61] | 'under' [0.39] a S -> NP VP [1.0] VP -> V NP [.59] VP -> V [.40] VP -> VP PP [.01] NP -> Det N [.41] NP -> Name [.28] NP -> NP PP [.31] PP -> P NP [1.0] V -> 'saw' [.21] V -> 'ate' [.51] V -> 'ran' [.28] N -> 'boy' [.11] N -> 'cookie' [.12] N -> 'table' [.13] N -> 'telescope' [.14] N -> 'hill' [.5] Name -> 'Jack' [.52] Name -> 'Bob' [.48] P -> 'with' [.61] P -> 'under' [.39] Det -> 'the' [.41] Det -> 'a' [.31] Det -> 'my' [.28] zI saw the man with my telescopez:the boy saw Jack with Bob under the table with a telescoperz>3z: z %rzWhich demo (%d-%d)? r1r2zBad sentence numberz sent: z parser: z grammar: c(||jzSrr,abs rr0zdemo..sALrz)Time (secs) # Parses Average P(parse)z)-----------------------------------------z%11.4f%11d%19.14fc(||jzSrr,rcs rr0zdemo..sAFFH rz*------------------------------------------z%11s%11d%19.14fzn/azDraw parses (y/n)? y) draw_treesz please wait...zPrint parses (y/n)? )systimenltkr_ nltk.grammarr` nltk.parser fromstringrrrintstdinreadlinestriprKr parse_allrfreezekeyslower startswithnltk.draw.treerh)rirjr_r`r toy_pcfg1 toy_pcfg2demosisnumsentr r"parser all_parsesr/parsesaverage num_parsesr?rhr)s rdemorIs!(  I I< +I6 EyQ E  G 3u:  Qr "U1Xa[M*+ i%(1+%&  As5z? 2<399%%'--/014d g ZZ\F 7 #FJ HTF*VHKy AB LLO A   f %F 99;?DFL(&!4s6{BRS VJ #!" 188:# G 56 56 z7 ; ;< __ F ,fa 83v; F  67 uc&k15 56 G S) yy!!#))+66s;-  !F G c* yy!!#))+66s; E %L <_ #$s <rs:"-n8Gn8l xv zFr