JL iMtdZddlZddlmZddlmZmZddlmZddl m Z m Z m Z m Z ddlmZmZGdd e ZGd d e ZGd d e ZGdde ZGdde ZGdde ZGddeZGddeZGddeZGddeZGddeZd dZedk(reyy)!a Classes and interfaces for associating probabilities with tree structures that represent the internal organization of a text. The probabilistic parser module defines ``BottomUpProbabilisticChartParser``. ``BottomUpProbabilisticChartParser`` is an abstract class that implements a bottom-up chart parser for ``PCFG`` grammars. It maintains a queue of edges, and adds them to the chart one at a time. The ordering of this queue is based on the probabilities associated with the edges, allowing the parser to expand more likely edges before less likely ones. Each subclass implements a different queue ordering, producing different search strategies. Currently the following subclasses are defined: - ``InsideChartParser`` searches edges in decreasing order of their trees' inside probabilities. - ``RandomChartParser`` searches edges in random order. - ``LongestChartParser`` searches edges in decreasing order of their location's length. The ``BottomUpProbabilisticChartParser`` constructor has an optional argument beam_size. If non-zero, this controls the size of the beam (aka the edge queue). This option is most useful with InsideChartParser. N)reduce)PCFG Nonterminal)ParserI)AbstractChartRuleChartLeafEdgeTreeEdge)ProbabilisticTreeTreeceZdZdZy)ProbabilisticLeafEdgecy)Ng?selfs W/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/nltk/parse/pchart.pyprobzProbabilisticLeafEdge.prob3sN)__name__ __module__ __qualname__rrrrrr2srrc(eZdZdZdZedZy)ProbabilisticTreeEdgecjtj|g|i|||_|j|f|_yN)r __init___prob_comparison_key)rrargskwargss rrzProbabilisticTreeEdge.__init__8s4$000 $ 4 4d;rc|jSr)rrs rrzProbabilisticTreeEdge.prob>s zzrc\t|||f|j|jdS)Nr)rlhsrhs) productionindexps rfrom_productionz%ProbabilisticTreeEdge.from_productionAs,$ u~z~~/1A1  rN)rrrrr staticmethodr)rrrrr7s <   rrceZdZdZdZy)ProbabilisticBottomUpInitRulerc#Kt|jD]4}t|j||}|j |ds1|6yw)Nr)range num_leavesrleafinsert)rchartgrammarr'new_edges rapplyz#ProbabilisticBottomUpInitRule.applyLsK5++-. E,UZZ->FH||Hb) s A A ANrrr NUM_EDGESr5rrrr,r,Is Irr,ceZdZdZdZy) ProbabilisticBottomUpPredictRulec#6K|jry|jD]q}|j|jdk(s(tj ||j |j}|j|dsn|syw)Nrr) is_incomplete productionsr$r%rr)startrr1)rr2r3edgeprodr4s rr5z&ProbabilisticBottomUpPredictRule.applyVs}     '') #DxxzTXXZ]*0@@$**, <<"-"N  #sA B ABBNr6rrrr9r9Ss I #rr9ceZdZdZdZy)ProbabilisticFundamentalRulec#:K|j|jk(rA|j|jk(r |j r|j sy|j |j z}t||j|jf|j|j|jdz}d}|j|D]}|j|||fzsd}|r|yyw)Nr:)spanr$r%dotFT) endr>nextsymr$r< is_completerrr%rFchild_pointer_listsr1) rr2r3 left_edge right_edger(r4 changed_chartcpl1s rr5z"ProbabilisticFundamentalRule.applyes MMOz//1 1!!#z~~'77'')&&(  NN z0 0( //#Z^^%56   !#   --i8 %D||Hdj]&:; $  % N s D D DNr6rrrrBrBbs IrrBc*eZdZdZeZdZdZy)&SingleEdgeProbabilisticFundamentalRuler:c#K|j}|jrR|j|jd|j D]}|j ||||Ed{ y|j|j d|jD]}|j ||||Ed{ y7Y7 w)NT)r>rIr$F)rGrIrH)_fundamental_ruler<selectrGrHr5r>r$)rr2r3edge1fredge2s rr5z,SingleEdgeProbabilisticFundamentalRule.applys  # #    iikt& B88E7E5AAA B KKMueiik& B88E7E5AAA BB Bs%A'C)C*AC;C<CCcy)NzFundamental Rulerrs r__str__z.SingleEdgeProbabilisticFundamentalRule.__str__s!rN)rrrr7rBrRr5rXrrrrPrPsI46 B"rrPc>eZdZdZd dZdZd dZdZdZdZ dZ y ) BottomUpProbabilisticChartParsera An abstract bottom-up parser for ``PCFG`` grammars that uses a ``Chart`` to record partial results. ``BottomUpProbabilisticChartParser`` maintains a queue of edges that can be added to the chart. This queue is initialized with edges for each token in the text that is being parsed. ``BottomUpProbabilisticChartParser`` inserts these edges into the chart one at a time, starting with the most likely edges, and proceeding to less likely edges. For each edge that is added to the chart, it may become possible to insert additional edges into the chart; these are added to the queue. This process continues until enough complete parses have been generated, or until the queue is empty. The sorting order for the queue is not specified by ``BottomUpProbabilisticChartParser``. Different sorting orders will result in different search strategies. The sorting order for the queue is defined by the method ``sort_queue``; subclasses are required to provide a definition for this method. :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. cdt|ts td||_||_||_y)a% Create a new ``BottomUpProbabilisticChartParser``, that uses ``grammar`` to parse texts. :type grammar: PCFG :param grammar: The grammar used to parse texts. :type beam_size: int :param beam_size: The maximum length for the parser's edge queue. :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. z&The grammar must be probabilistic PCFGN) isinstancer ValueError_grammar beam_size_trace)rr3r_traces rrz)BottomUpProbabilisticChartParser.__init__s/'4(EF F " rc|jSr)r^rs rr3z(BottomUpProbabilisticChartParser.grammars }}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`)rras rraz&BottomUpProbabilisticChartParser.traces  rc|jj|tt|}|j}t }t }t }g}|j||D]T}|jdkDr2td|j|ddd|jd|j|Vt|dkDr|j|||jr|j!|||j#}|jdkDr2td|j|ddd|jd|j%|j||||j%|j|||t|dkDrt|j'|j)t*} i} |j-D]3} | j| | j/| j1f<5| D]} |j3| | | j5d d t7| S) Nr:z rC)width50z []rTc"|jSrr)trees rz8BottomUpProbabilisticChartParser.parse..s 499;r)reversekey)r^check_coveragerlistr,r9rPr5r`printpretty_format_edgerappendlen sort_queuer__prunepopextendparsesr>r r=r$r%_setprobsortiter) rtokensr2r3bu_initburUqueuer?rx prod_probsr@parses rrz&BottomUpProbabilisticChartParser.parses $$V,d6l#--01 - / 3 5MM%1 D{{Q//A/> M LL   %j1n OOE5 )~~ E5)99;D{{Q//A/> M LL%$7 8 LL%$7 8%%j1n*ell7==?4EFG '') =D15Jtxxz488:- . = -E MM% , -  D&> ?F|rc|jyt|j}g}|D]L}t|tr)|j t|j<|j |N||t |f}|D]8}t|ts|j||||jz}:|j|yr) rrlabelr\r rrtupleryset_prob)rrjrr$r%childrs rryz)BottomUpProbabilisticChartParser._setprobs 99; " $**,' "E%& ;u{{}56 5!  " #uSz/* %E%& eZ0 $ % drct)a Sort the given queue of ``Edge`` objects, placing the edge that should be tried first at the beginning of the queue. This method will be called after each ``Edge`` is added to the queue. :param queue: The queue of ``Edge`` objects to sort. Each edge in this queue is an edge that could be added to the chart by the fundamental rule; but that has not yet been added. :type queue: list(Edge) :param chart: The chart being used to parse the text. This chart can be used to provide extra information for sorting the queue. :type chart: Chart :rtype: None )NotImplementedErrorrrr2s rrtz+BottomUpProbabilisticChartParser.sort_queue,s "##rct||jkDrUt||jz }|jdkDr(|d|D] }td|j |dz"|d|=yy)z@Discard items in the queue if the queue is longer than the beam.rCNz %-50s [DISCARDED])rsr_r`rprq)rrr2splitr?s rruz'BottomUpProbabilisticChartParser._prune>sr u: &J/E{{Q!&5MUD/%2J2J4QR2SSTUfuf 'rN)rr)rC) rrr__doc__rr3rarryrtrurrrrZrZs+4* 7r,$$rrZceZdZdZdZy)InsideChartParseraU A bottom-up parser for ``PCFG`` grammars that tries edges in descending order of the inside probabilities of their trees. The "inside probability" of a tree is simply the probability of the entire tree, ignoring its context. In particular, the inside probability of a tree generated by production *p* with children *c[1], c[2], ..., c[n]* is *P(p)P(c[1])P(c[2])...P(c[n])*; and the inside probability of a token is 1 if it is present in the text, and 0 if it is absent. This sorting order results in a type of lowest-cost-first search strategy. c*|jdy)aD Sort the given queue of edges, in descending order of the inside probabilities of the edges' trees. :param queue: The queue of ``Edge`` objects to sort. Each edge in this queue is an edge that could be added to the chart by the fundamental rule; but that has not yet been added. :type queue: list(Edge) :param chart: The chart being used to parse the text. This chart can be used to provide extra information for sorting the queue. :type chart: Chart :rtype: None c"|jSrrir?s rrkz.InsideChartParser.sort_queue..hs DIIKrrmNrzrs rrtzInsideChartParser.sort_queueYs  / 0rNrrrrrtrrrrrHs   1rrceZdZdZdZy)RandomChartParserz A bottom-up parser for ``PCFG`` grammars that tries edges in random order. This sorting order results in a random search strategy. cjtjdt|dz }|||dc|d<||<y)Nrr:)randomrandintrs)rrr2is rrtzRandomChartParser.sort_queues6 NN1c%j1n -!&q59rE!HrNrrrrrrs  6rrceZdZdZdZy)UnsortedChartParserzV A bottom-up parser for ``PCFG`` grammars that tries edges in whatever order. cyrrrs rrtzUnsortedChartParser.sort_queuesrNrrrrrrs  rrceZdZdZdZy)LongestChartParserz A bottom-up parser for ``PCFG`` grammars that tries longer edges before shorter ones. This sorting order results in a type of best-first search strategy. c*|jdy)Nc"|jSr)lengthrs rrkz/LongestChartParser.sort_queue..s DKKMrrrrs rrtzLongestChartParser.sort_queues 1 2rNrrrrrrs 3rrc 2ddl}ddl}ddlm}ddlm}t jd}t jd}d|fd|fg} |ttt| D]:} t| d zd d | | dtd | | d zt<td d t| fzdt|jjjd z } | |\} } | j} |j!| |j#| |j%| |j'| |j!| t| d zg}g}g}g}i}|D]}td| d|d| |j)d|j}t+|j-| }|j/|j|z |rt1d|dt|z nd}|j/||j/t||D]}d ||j3<ttdtdtt|D]B} td|| j4j6|| j8|| || || fzD|j;}|rt1d|dt|z }nd}tdtdddt||fz|\ttdd|jjjj=j?d}|rdd l m!}td!|||\ttd"d|jjjj=j?d}|r|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)pcharta7 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 John with my telescopez:the boy saw Jack with Bob under the table with a telescoper:z>3z: z %rzWhich demo (%d-%d)?  )rGzBad sentence number)r_z s: z parser: z grammar: c(||jzSrriabs rrkzdemo..AFFH rzC Parser Beam | Time (secs) # Parses Average P(parse)zC------------------------+------------------------------------------z%18s %4d |%11.4f%11d%19.14fc(||jzSrrirs rrkzdemo..'rrz%18s |%11s%11d%19.14fz (All Parses)zn/azDraw parses (y/n)? y) draw_treesz please wait...zPrint parses (y/n)? )"systimenltkr nltk.parserr fromstringrpr.rsintstdinreadlinestriprrrrrrarorrrrfreeze __class__rr_keyslower startswithnltk.draw.treer)choice draw_parses print_parsesrrrr toy_pcfg1 toy_pcfg2demosrsentr3r|parserstimes average_p num_parses all_parsesparsertrxr(rrs rdemors!  I I: (3 EyQ E ~ s5z" A QU2Jbq! . / )eAhqk) * G  $3u:6C@SYY'')//12Q6f g ZZ\F   )  )""7+!!'*  CK!O D G EIJJ ' dV:fX[ BC Q IIKfll6*+ TYY[1_%JPF,fa 83v; FVW#f+& 'A%&Jqxxz " ' ' G OP OP 3w<   ) $$-- $$a1 !     __ F ,fa 83v; F  OP &.%Va)P PQ  #-ii((*00288:EEcJ -  !F  $#.yy))+11399;FFsK  E %L Q #$s 4P P__main__)NNN)rr functoolsr nltk.grammarrrnltk.parse.apirnltk.parse.chartrrr r nltk.treer r rrr,r9rBrPrZrrrrrrrrrrs>*"II-H  H $$5 #'8 ##4D"->"0iwiX 18 1~ 68 6: 39 3"Qh zFr