ó <¿CVc@s ddlmZmZddlmZddlmZmZmZddl m Z ddl m Z ddl mZmZeedefd„ƒYƒƒZed efd „ƒYƒZd efd „ƒYZd efd„ƒYZd„Zd„Zd„Zd„ZedkreƒndS(iÿÿÿÿ(tprint_functiontunicode_literals(t defaultdict(tDependencyProductiontDependencyGrammartProbabilisticDependencyGrammar(tDependencyGraph(traise_unorderable_types(ttotal_orderingtpython_2_unicode_compatibletDependencySpancBsVeZdZd„Zd„Zd„Zd„Zd„Zd„Zd„Z d„Z RS( uT A contiguous span over some part of the input string representing dependency (head -> modifier) relationships amongst words. An atomic span corresponds to only one word so it isn't a 'span' in the conventional sense, as its _start_index = _end_index = _head_index for concatenation purposes. All other spans are assumed to have arcs between all nodes within the start and end indexes of the span, and one head index corresponding to the head word for the entire span. This is the same as the root node if the dependency structure were depicted as a graph. cCs^||_||_||_||_||_|||t|ƒf|_t|jƒ|_dS(N( t _start_indext _end_indext _head_indext_arcst_tagsttuplet_comparison_keythasht_hash(tselft start_indext end_indext head_indextarcsttags((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__init__$s     cCs|jS(uk :return: An value indexing the head of the entire ``DependencySpan``. :rtype: int (R (R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR-scCsd|j|j|jfS(uj :return: A concise string representatino of the ``DependencySpan``. :rtype: str. uSpan %d-%d; Head Index: %d(R R R (R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__repr__4scCsed|j|j|jf}xBtt|jƒƒD]+}|d||j||j|f7}q2W|S(ui :return: A verbose string representation of the ``DependencySpan``. :rtype: str uSpan %d-%d; Head Index: %du %d <- %d, %s(R R R trangetlenRR(Rtstrti((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__str__;s)cCs(t|ƒt|ƒko'|j|jkS(N(ttypeR(Rtother((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__eq__EscCs ||k S(N((RR"((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__ne__IscCs2t|tƒs"td||ƒn|j|jkS(Nu<(t isinstanceR RR(RR"((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__lt__LscCs|jS(uE :return: The hash value of this ``DependencySpan``. (R(R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt__hash__Qs( t__name__t __module__t__doc__RRRR R#R$R&R'(((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR s      t ChartCellcBs2eZdZd„Zd„Zd„Zd„ZRS(uå A cell from the parse chart formed when performing the CYK algorithm. Each cell keeps track of its x and y coordinates (though this will probably be discarded), and a list of spans serving as the cell's entries. cCs%||_||_tgƒ|_dS(u :param x: This cell's x coordinate. :type x: int. :param y: This cell's y coordinate. :type y: int. N(t_xt_ytsett_entries(Rtxty((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRbs  cCs|jj|ƒdS(u¶ Appends the given span to the list of spans representing the chart cell's entries. :param span: The span to add. :type span: DependencySpan N(R/tadd(Rtspan((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR2mscCsd|j|j|jfS(uf :return: A verbose string representation of this ``ChartCell``. :rtype: str. u CC[%d,%d]: %s(R,R-R/(R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR wscCsd|S(uf :return: A concise string representation of this ``ChartCell``. :rtype: str. u%s((R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR~s(R(R)R*RR2R R(((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR+[s  tProjectiveDependencyParsercBs)eZdZd„Zd„Zd„ZRS(u¦ A projective, rule-based, dependency parser. A ProjectiveDependencyParser is created with a DependencyGrammar, a set of productions specifying word-to-word dependency relations. The parse() method will then return the set of all parses, in tree representation, for a given input sequence of tokens. Each parse must meet the requirements of the both the grammar and the projectivity constraint which specifies that the branches of the dependency tree are not allowed to cross. Alternatively, this can be understood as stating that each parent node and its children in the parse tree form a continuous substring of the input sequence. cCs ||_dS(u Create a new ProjectiveDependencyParser, from a word-to-word dependency grammar ``DependencyGrammar``. :param dependency_grammar: A word-to-word relation dependencygrammar. :type dependency_grammar: DependencyGrammar N(t_grammar(Rtdependency_grammar((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR˜sc csKt|ƒ|_g}xºtdt|jƒdƒD]œ}|jgƒx†tdt|jƒdƒD]h}||jt||ƒƒ||dkrb|||jt|d||ddgdgƒƒqbqbWq2WxÐtdt|jƒdƒD]²}x©t|dddƒD]‘}xˆt|d|dƒD]p}xg|||jD]T}xK|||jD]8}x/|j ||ƒD]}|||j|ƒqrWqYWqAWq)Wq WqïWxŸ|t|jƒdjD]ƒ} d} x]tt|ƒƒD]I}| d|d||||ddd| j |ddd d f 7} qßWt | ƒ} | j ƒVqÀWd S( u> Performs a projective dependency parse on the list of tokens using a chart-based, span-concatenation algorithm similar to Eisner (1996). :param tokens: The list of input tokens. :type tokens: list(str) :return: An iterator over parse trees. :rtype: iter(Tree) iiiÿÿÿÿunulliuu %d %s %s %s %s %s %d %s %s %s uROOTu-N( tlistt_tokensRRtappendR+R2R R/t concatenateRRttree( RttokenstchartRtjtktspan1tspan2tnewspantparset conll_formattdg((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRC¢s* # #@#-!G cCsVg}|j|jkr%tdƒn|j|jkrL|}|}|}n|j|j}|j|j}|jj|j|j|j|jƒr×|j||j|j<|jt |j|j |j||ƒƒn|j|j}|jj|j|j|j|jƒrR|j||j|j<|jt |j|j |j||ƒƒn|S(u Concatenates the two spans in whichever way possible. This includes rightward concatenation (from the leftmost word of the leftmost span to the rightmost word of the rightmost span) and leftward concatenation (vice-versa) between adjacent spans. Unlike Eisner's presentation of span concatenation, these spans do not share or pivot on a particular word/word-index. :return: A list of new spans formed through concatenation. :rtype: list(DependencySpan) u8Error: Mismatched spans - replace this with thrown error( R tprintRRR5tcontainsR8R R9R R (RR@RAtspanst temp_spantnew_arcstnew_tags((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR:Ês"   )+)+(R(R)R*RRCR:(((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR4‹s  (t'ProbabilisticProjectiveDependencyParsercBs;eZdZd„Zd„Zd„Zd„Zd„ZRS(u¼A probabilistic, projective dependency parser. This parser returns the most probable projective parse derived from the probabilistic dependency grammar derived from the train() method. The probabilistic model is an implementation of Eisner's (1996) Model C, which conditions on head-word, head-tag, child-word, and child-tag. The decoding uses a bottom-up chart-based span concatenation algorithm that's identical to the one utilized by the rule-based projective parser. Usage example ------------- >>> from nltk.parse.dependencygraph import conll_data2 >>> graphs = [ ... DependencyGraph(entry) for entry in conll_data2.split('\n\n') if entry ... ] >>> ppdp = ProbabilisticProjectiveDependencyParser() >>> ppdp.train(graphs) >>> sent = ['Cathy', 'zag', 'hen', 'wild', 'zwaaien', '.'] >>> list(ppdp.parse(sent)) [Tree('zag', ['Cathy', 'hen', Tree('zwaaien', ['wild', '.'])])] cCsdS(up Create a new probabilistic dependency parser. No additional operations are necessary. N((R((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR scCs%t|ƒ|_g}xtdt|jƒdƒD]ö}|jgƒxàtdt|jƒdƒD]Â}||jt||ƒƒ||dkrb||d|jjkrxr|jj||dD];}|||jt |d||ddg|gƒƒqÅWq$t d||dƒgSqbqbWq2WxÐtdt|jƒdƒD]²}x©t|dddƒD]‘}xˆt|d|dƒD]p}xg|||j D]T}xK|||j D]8}x/|j ||ƒD]} |||j| ƒqÌWq³Wq›WqƒWqfWqIWg} d } d} xù|t|jƒdj D]Ý} d}d}x”tt|ƒƒD]€}|d||d| j|ddf7}|d |d||||| j|| j|d| j|dd d d f 7}qQWt|ƒ}|j|ƒ}| j||jƒfƒq,W| jƒd „| DƒS(uX Parses the list of tokens subject to the projectivity constraint and the productions in the parser's grammar. This uses a method similar to the span-concatenation algorithm defined in Eisner (1996). It returns the most probable parse derived from the parser's probabilistic dependency grammar. iiiÿÿÿÿu7No tag found for input token '%s', parse is impossible.iuu %s %s %d %s unullu %d %s %s %s %s %s %d %s %s %s uROOTu-css|]\}}|VqdS(N((t.0tscoreR;((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pys >sN(R7R8RRR9R+R5RR2R RFR/R:tNoneRRt compute_probR;tsort(RR<R=RR>ttagR?R@RARBttreest max_parset max_scoreRCRDt malt_formatRERN((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRCsB# #<#-!)U  cCsfg}|j|jkr%tdƒn|j|jkrL|}|}|}n|j|j}|j|j}|jj|j|j|j|jƒr×|j||j|j<|jt |j|j |j||ƒƒn|j|j}|j|j}|jj|j|j|j|jƒrb|j||j|j<|jt |j|j |j||ƒƒn|S(u Concatenates the two spans in whichever way possible. This includes rightward concatenation (from the leftmost word of the leftmost span to the rightmost word of the rightmost span) and leftward concatenation (vice-versa) between adjacent spans. Unlike Eisner's presentation of span concatenation, these spans do not share or pivot on a particular word/word-index. :return: A list of new spans formed through concatenation. :rtype: list(DependencySpan) u8Error: Mismatched spans - replace this with thrown error( R RFRRR5RGR8R R9R R (RR@RARHRIRJRK((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyR:As$   )+)+c CsXg}ttƒ}i}x$|D]}xtdt|jƒƒD]ù}tt|j|djƒƒgƒ}|j|ƒ}|j |ƒ} || } x¢td|d| dƒD]…} |j|d} |j|d} | |krö|| j | ƒnt | gƒ|| WqWt|||ƒ|_dS(uƒ Trains a ProbabilisticDependencyGrammar based on the list of input DependencyGraphs. This model is an implementation of Eisner's (1996) Model C, which derives its statistics from head-word, head-tag, child-word, and child-tag relationships. :param graphs: A list of dependency graphs to train from. :type: list(DependencyGraph) iudepsiiuwordutaguSTOPuSTARTiÿÿÿÿu'(head (%s %s) (mods (%s, %s, %s) left))u(mods (%s, %s, %s) left))u((head (%s %s) (mods (%s, %s, %s) right))u(mods (%s, %s, %s) right))N(RtintRRtnodestsumR7tvaluest left_childrentright_childrenR2R.R9RRR5(Rtgraphst productionsteventsRREt node_indextchildrentnr_left_childrentnr_right_childrent nr_childrent child_indext head_wordthead_tagtchildt child_tagt prev_wordtprev_tagt array_indext head_eventt mod_event((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyttrainbs`   & "          cCsãd}xÖtdt|jƒƒD]¼}tt|j|djƒƒgƒ}|j|ƒ}|j|ƒ}||}xetd|d|dƒD]H}|j|d} |j|d} d} d} d } d }|dkrÑ||}|dkr|j||d} |j||d} n|d kr_|j||dd} |j||dd}nd | | || | f}d || | f}|jj |}|jj |}|dkrÈ|||9}q×d }q|dkr||d}||kr$|j||d} |j||d} n|dkre|j||dd} |j||dd}nd| | || | f}d|| | f}|jj |}|jj |}|dkrÎ|||9}q×d }qqWqW|S(uS Computes the probability of a dependency graph based on the parser's probability model (defined by the parser's statistical dependency grammar). :param dg: A dependency graph to score. :type dg: DependencyGraph :return: The probability of the dependency graph. :rtype: int gð?iudepsiiuwordutaguSTOPuSTARTiÿÿÿÿu'(head (%s %s) (mods (%s, %s, %s) left))u(mods (%s, %s, %s) left))g:Œ0âŽyE>u((head (%s %s) (mods (%s, %s, %s) right))u(mods (%s, %s, %s) right))( RRRXRYR7RZR[R\R5t_events(RREtprobR`RaRbRcRdReRfRgRhRiRjRkRlRmRnth_counttm_count((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRP¡sX & "          (R(R)R*RRCR:RoRP(((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRLòs   . ! ?cCstƒtƒdS(N(tprojective_rule_parse_demotprojective_prob_parse_demo(((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pytdemoçscCsbtjdƒ}t|ƒt|ƒ}|jdddddgƒ}x|D]}t|ƒqJWdS(uƒ A demonstration showing the creation and use of a ``DependencyGrammar`` to perform a projective dependency parse. uP 'scratch' -> 'cats' | 'walls' 'walls' -> 'the' 'cats' -> 'the' utheucatsuscratchuwallsN(Rt fromstringRFR4RC(tgrammartpdpRSR;((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRtís    cCsFtƒtdƒtdƒtdƒtjdƒ}t|ƒtƒtdƒtdƒt|ƒ}|jddd dd d gƒ}x|D]}t|ƒqWtƒtd ƒtd ƒtdƒtdƒtjdƒ}t|ƒtƒtdƒt|ƒ}|jddd dd d gƒ}x|D]}t|ƒq.WdS(u A demonstration showing the creation of a ``DependencyGrammar`` in which a specific number of modifiers is listed for a given head. This can further constrain the number of possible parses created by a ``ProjectiveDependencyParser``. u>A grammar with no arity constraints. Each DependencyProductionu;specifies a relationship between one head word and only oneumodifier word.uj 'fell' -> 'price' | 'stock' 'price' -> 'of' | 'the' 'of' -> 'stock' 'stock' -> 'the' u<For the sentence 'The price of the stock fell', this grammaru(will produce the following three parses:utheupriceuofustockufellu.By contrast, the following grammar contains a u2DependencyProduction that specifies a relationshipu5between a single head word, 'price', and two modifieruwords, 'of' and 'the'.uh 'fell' -> 'price' | 'stock' 'price' -> 'of' 'the' 'of' -> 'stock' 'stock' -> 'the' u:This constrains the number of possible parses to just one:N(RFRRwR4RC(RxRyRSR;((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pytarity_parse_demoþs8        !         ! cCsÁddlm}g|jdƒD]}|r t|ƒ^q }tƒ}tdƒ|j|ƒddddd d g}td d j|ƒd ƒtdƒx!|j|ƒD]}t|ƒq©WdS(uT A demo showing the training and use of a projective dependency parser. iÿÿÿÿ(t conll_data2u u6Training Probabilistic Projective Dependency Parser...uCathyuzaguhenuwilduzwaaienu.u Parsing 'u u'...uParse:N( tnltk.parse.dependencygraphR{tsplitRRLRFRotjoinRC(R{tentryR]tppdptsentR;((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyRu.s+    u__main__N(t __future__RRt collectionsRt nltk.grammarRRRR|Rtnltk.internalsRt nltk.compatRR tobjectR R+R4RLRvRtRzRuR((((sw/private/var/folders/cc/xm4nqn811x9b50x1q_zpkmvdjlphkp/T/pip-build-FUwmDn/nltk/nltk/parse/projectivedependencyparser.pyt s$B/gõ   0