
    g8                     ~   d Z ddlZddlmZmZmZmZ ddlm	Z	m
Z
 ddlmZ ddlmZ  G d d      Z G d	 d
e      Z G d de      Z G d de      ZddZedk(  rEddlZddlmZ 	  edej.                  d   z         Z	  edej.                  d   z         Z eee       g dZy# e$ r dZY 0w xY w# e$ r dZY $w xY w)a  
Tools to identify collocations --- words that often appear consecutively
--- within corpora. They may also be used to find other associations between
word occurrences.
See Manning and Schutze ch. 5 at https://nlp.stanford.edu/fsnlp/promo/colloc.pdf
and the Text::NSP Perl package at http://ngram.sourceforge.net

Finding collocations requires first calculating the frequencies of words and
their appearance in the context of other words. Often the collection of words
will then requiring filtering to only retain useful content terms. Each ngram
of words may then be scored according to some association measure, in order
to determine the relative likelihood of each ngram being a collocation.

The ``BigramCollocationFinder`` and ``TrigramCollocationFinder`` classes provide
these functionalities, dependent on being provided a function which scores a
ngram given appropriate frequency counts. A number of standard association
measures are provided in bigram_measures and trigram_measures.
    N)BigramAssocMeasuresContingencyMeasuresQuadgramAssocMeasuresTrigramAssocMeasures)ranks_from_scoresspearman_correlation)FreqDist)ngramsc                       e Zd ZdZd Ze	 dd       Zed        Zed        Z	d fdZ
d	 Zd
 Zd Zd Zd Zd Zd Zy)AbstractCollocationFindera  
    An abstract base class for collocation finders whose purpose is to
    collect collocation candidate frequencies, filter and rank them.

    As a minimum, collocation finders require the frequencies of each
    word in a corpus, and the joint frequency of word tuples. This data
    should be provided through nltk.probability.FreqDist objects or an
    identical interface.
    c                 J    || _         |j                         | _        || _        y N)word_fdNngram_fd)selfr   r   s      F/var/www/openai/venv/lib/python3.12/site-packages/nltk/collocations.py__init__z"AbstractCollocationFinder.__init__:   s         Nc                     |f|dz
  z  |r(t         j                  j                  fd|D              S |r(t         j                  j                  fd|D              S y)zU
        Pad the document with the place holder according to the window_size
           c              3   J   K   | ]  }t        j                  |        y wr   
_itertoolschain.0docpaddings     r   	<genexpr>zAAbstractCollocationFinder._build_new_documents.<locals>.<genexpr>H   s"      2:C3
  g.)    #c              3   J   K   | ]  }t        j                  |        y wr   r   r   s     r   r    zAAbstractCollocationFinder._build_new_documents.<locals>.<genexpr>L   s"      2:C3
  #.)r!   N)r   r   from_iterable)cls	documentswindow_sizepad_left	pad_right
pad_symbolr   s         @r   _build_new_documentsz.AbstractCollocationFinder._build_new_documents?   sn     -;?3##11 2:C2   ##11 2:C2   r   c                 \    | j                  | j                  || j                  d            S )zConstructs a collocation finder given a collection of documents,
        each of which is a list (or iterable) of tokens.
        Tr(   )
from_wordsr*   
default_ws)r$   r%   s     r   from_documentsz(AbstractCollocationFinder.from_documentsP   s.     ~~$$Y$$O
 	
r   c                 Z     t         fdt        t               dz
        D              S )Nc              3   @   K   | ]  }t        ||z            y wr   )tuple)r   inwordss     r   r    z<AbstractCollocationFinder._ngram_freqdist.<locals>.<genexpr>\   s$     O9NAeAA./9Ns   r   )r	   rangelen)r5   r4   s   ``r   _ngram_freqdistz)AbstractCollocationFinder._ngram_freqdistZ   s!    Os5zA~9NOOOr   c                      y)NF )ngramfreqs     r   <lambda>z"AbstractCollocationFinder.<lambda>^   s    5r   c                     t               }| j                  j                         D ]  \  }} |||      r|||<    || _        y)zGeneric filter removes ngrams from the frequency distribution
        if the function returns True when passed an ngram tuple.
        N)r	   r   items)r   fn	tmp_ngramr;   r<   s        r   _apply_filterz'AbstractCollocationFinder._apply_filter^   sB     J	==..0KE4eT?#'	%  1 "r   c                 .    | j                  fd       y)zARemoves candidate ngrams which have frequency less than min_freq.c                     |k  S r   r:   )ngr<   min_freqs     r   r=   z=AbstractCollocationFinder.apply_freq_filter.<locals>.<lambda>j   s	    D8Or   NrB   )r   rF   s    `r   apply_freq_filterz+AbstractCollocationFinder.apply_freq_filterh   s    ;<r   c                 .    | j                  fd       y)z`Removes candidate ngrams (w1, w2, ...) where fn(w1, w2, ...)
        evaluates to True.
        c                      |  S r   r:   rE   fr@   s     r   r=   z>AbstractCollocationFinder.apply_ngram_filter.<locals>.<lambda>p   s	    Rr   NrG   r   r@   s    `r   apply_ngram_filterz,AbstractCollocationFinder.apply_ngram_filterl   s     	01r   c                 .    | j                  fd       y)zmRemoves candidate ngrams (w1, w2, ...) where any of (fn(w1), fn(w2),
        ...) evaluates to True.
        c                 ,    t        fd| D              S )Nc              3   .   K   | ]  } |        y wr   r:   )r   wr@   s     r   r    zPAbstractCollocationFinder.apply_word_filter.<locals>.<lambda>.<locals>.<genexpr>v   s     ,?BqRUBs   )anyrK   s     r   r=   z=AbstractCollocationFinder.apply_word_filter.<locals>.<lambda>v   s    ,?B,?)?r   NrG   rM   s    `r   apply_word_filterz+AbstractCollocationFinder.apply_word_filterr   s     	?@r   c              #   f   K   | j                   D ]  } | j                  |g| }|||f   yw)zbGenerates of (ngram, score) pairs as determined by the scoring
        function provided.
        N)r   score_ngram)r   score_fntupscores       r   _score_ngramsz'AbstractCollocationFinder._score_ngramsx   s=      ==C$D$$X44E 5j  !s   %1	1c                 <    t        | j                  |      d       S )zReturns a sequence of (ngram, score) pairs ordered from highest to
        lowest score, as determined by the scoring function provided.
        c                     | d    | d   fS )Nr   r   r:   )ts    r   r=   z8AbstractCollocationFinder.score_ngrams.<locals>.<lambda>   s    AaD5!A$-r   )key)sortedrZ   )r   rW   s     r   score_ngramsz&AbstractCollocationFinder.score_ngrams   s     d((28OPPr   c                 \    | j                  |      d| D cg c]  \  }}|	 c}}S c c}}w )z;Returns the top n ngrams when scored by the given function.Nr`   )r   rW   r4   pss        r   nbestzAbstractCollocationFinder.nbest   s2    "//9"1=>=da=>>>s   (c              #   T   K   | j                  |      D ]  \  }}||kD  r|  y yw)z}Returns a sequence of ngrams, ordered by decreasing score, whose
        scores each exceed the given minimum score.
        Nrb   )r   rW   	min_scorer;   rY   s        r   above_scorez%AbstractCollocationFinder.above_score   s1      !--h7LE5y 	 8s   &()FFN)__name__
__module____qualname____doc__r   classmethodr*   r/   staticmethodr8   rB   rH   rN   rT   rZ   r`   re   rh   r:   r   r   r   r   /   s|    !
 QU   
 
 P P  9 "=2A!Q?r   r   c                   4    e Zd ZdZdZddZedd       Zd Zy)BigramCollocationFinderzA tool for the finding and ranking of bigram collocations or other
    association measures. It is often useful to use from_words() rather than
    constructing an instance directly.
       c                 @    t         j                  | ||       || _        y)zConstruct a BigramCollocationFinder, given FreqDists for
        appearances of words and (possibly non-contiguous) bigrams.
        N)r   r   r&   )r   r   	bigram_fdr&   s       r   r   z BigramCollocationFinder.__init__   s     	"**4)D&r   c                     t               }t               }|dk  rt        d      t        ||d      D ]3  }|d   }|||xx   dz  cc<   |dd D ]  }||||fxx   dz  cc<    5  | |||      S )	zConstruct a BigramCollocationFinder for all bigrams in the given
        sequence.  When window_size > 2, count non-contiguous bigrams, in the
        style of Church and Hanks's (1990) association ratio.
        rq   zSpecify window_size at least 2Tr,   r   Nr   )r&   )r	   
ValueErrorr
   )r$   r5   r&   wfdbfdwindoww1w2s           r   r-   z"BigramCollocationFinder.from_words   s     jj?=>>UK4@FBzGqLGQRj>RMQ&M ! A 355r   c                     | j                   }| j                  ||f   | j                  dz
  z  }|sy| j                  |   }| j                  |   } ||||f|      S )zReturns the score for a given bigram using the given scoring
        function.  Following Church and Hanks (1990), counts are scaled by
        a factor of 1/(window_size - 1).
        g      ?N)r   r   r&   r   )r   rW   ry   rz   n_alln_iin_ixn_xis           r   rV   z#BigramCollocationFinder.score_ngram   sd    
 }}b"X&$*:*:S*@A||B||BtTlE22r   N)rq   	ri   rj   rk   rl   r.   r   rm   r-   rV   r:   r   r   rp   rp      s,    
 J' 6 6*3r   rp   c                   8    e Zd ZdZdZd Zedd       Zd Zd Z	y)	TrigramCollocationFinderzA tool for the finding and ranking of trigram collocations or other
    association measures. It is often useful to use from_words() rather than
    constructing an instance directly.
       c                 N    t         j                  | ||       || _        || _        y)zConstruct a TrigramCollocationFinder, given FreqDists for
        appearances of words, bigrams, two words with any word between them,
        and trigrams.
        N)r   r   wildcard_fdrs   )r   r   rs   r   
trigram_fds        r   r   z!TrigramCollocationFinder.__init__   s%    
 	"**4*E&"r   c                    |dk  rt        d      t               }t               }t               }t               }t        ||d      D ]l  }|d   }|t        j                  |dd d      D ]F  \  }	}
||xx   dz  cc<   |	|||	fxx   dz  cc<   |
(|||
fxx   dz  cc<   |||	|
fxx   dz  cc<   H n  | ||||      S )	z]Construct a TrigramCollocationFinder for all trigrams in the given
        sequence.
        r   zSpecify window_size at least 3Tr,   r   Nr   rq   ru   r	   r
   r   combinations)r$   r5   r&   rv   wildfdrw   tfdrx   ry   rz   w3s              r   r-   z#TrigramCollocationFinder.from_words   s    
 ?=>>jjjUK4@FBz$11&*a@BB1:RH":Bx A% RRL!Q&! A	 A 3VS))r   c                 B    t        | j                  | j                        S )zConstructs a bigram collocation finder with the bigram and unigram
        data from this finder. Note that this does not include any filtering
        applied to this finder.
        )rp   r   rs   )r   s    r   bigram_finderz&TrigramCollocationFinder.bigram_finder   s    
 't||T^^DDr   c                 &   | j                   }| j                  |||f   }|sy| j                  ||f   }| j                  ||f   }| j                  ||f   }	| j                  |   }
| j                  |   }| j                  |   } |||||	f|
||f|      S )zXReturns the score for a given trigram using the given scoring
        function.
        N)r   r   rs   r   r   )r   rW   ry   rz   r   r|   n_iiin_iixn_ixin_xiin_ixxn_xixn_xxis                r   rV   z$TrigramCollocationFinder.score_ngram   s     r2rl+Bx(  "b*Bx(R R R ue4ueU6KUSSr   N)r   )
ri   rj   rk   rl   r.   r   rm   r-   r   rV   r:   r   r   r   r      s3    
 J# * *4ETr   r   c                   2    e Zd ZdZdZd Zedd       Zd Zy)QuadgramCollocationFinderzA tool for the finding and ranking of quadgram collocations or other association measures.
    It is often useful to use from_words() rather than constructing an instance directly.
       c	                     t         j                  | ||       || _        || _        || _        || _        || _        || _        y)zConstruct a QuadgramCollocationFinder, given FreqDists for appearances of words,
        bigrams, trigrams, two words with one word and two words between them, three words
        with a word between them in both variations.
        N)r   r   iiiiiixiixxiiixiixii)	r   r   quadgram_fdr   r   r   r   r   r   s	            r   r   z"QuadgramCollocationFinder.__init__  s@    
 	"**4+F			r   c           
      b   |dk  rt        d      t               }t               }t               }t               }t               }t               }t               }	t               }
t        ||d      D ]  }|d   }|t        j                  |dd  d      D ]  \  }}}||xx   dz  cc<   ||||fxx   dz  cc<   |)||||fxx   dz  cc<   |||fxx   dz  cc<   |K|||||fxx   dz  cc<   |||fxx   dz  cc<   |
|||fxx   dz  cc<   |	|||fxx   dz  cc<      | |||||||	|
      S )Nr   zSpecify window_size at least 4Tr,   r   r   r   r   )r$   r5   r&   ixxxiiiir   r   r   r   r   r   rx   ry   rz   r   w4s                   r   r-   z$QuadgramCollocationFinder.from_words!  sg   ?=>>zzZjjzzzUK4@FBz(55fQRj!D
BRA:B8!:RRL!Q&!RH":b"b"%&!+&b"X!#b"b\"a'"b"b\"a'" E	 A( 4r3T4>>r   c           
      N   | j                   }| j                  ||||f   }|sy | j                  |||f   }| j                  |||f   }	| j                  |||f   }
| j                  |||f   }| j
                  ||f   }| j
                  ||f   }| j
                  ||f   }| j                  ||f   }| j                  ||f   }| j                  ||f   }| j                  |   }| j                  |   }| j                  |   }| j                  |   } ||||
||	f||||||f||||f|      S r   )	r   r   r   r   r   r   r   r   r   )r   rW   ry   rz   r   r   r|   n_iiiin_iiixn_xiiin_iixin_ixiin_iixxn_xxiin_xiixn_ixixn_ixxin_xixin_ixxxn_xixxn_xxixn_xxxis                         r   rV   z%QuadgramCollocationFinder.score_ngramD  sW   BB/02r2,'2r2,'BB<(BB<("b""b""b"2r(#B8$2r(#b!b!b!b!VVV,VVVVV<VVV,
 	
r   N)r   r   r:   r   r   r   r     s-     J  ?  ?D
r   r   c           
         ddl m}m}m} | |j                  } ||j
                  }ddlm}m} |j                  d      fd}|j                         D ]  }|j                  |      D 	cg c]  }	|	j                          }
}	t        j                  |
      }|j                  d       |j                  |        | ||j!                  |              ||j!                  |                  }t#        |       t#        d|j%                  | d	      D cg c]  }d
j'                  |       c}       t#        d|j(                   d|d        yc c}	w c c}w )z=Finds bigram collocations in the files of the WebText corpus.r   )r   r   r   N)	stopwordswebtextenglishc                 H    t        |       dk  xs | j                         v S )Nr   )r7   lower)rR   ignored_wordss    r   r=   zdemo.<locals>.<lambda>r  s     CFQJD!'')}*DDr   r   	    z	 Correlation to z: z0.4f)nltk.metricsr   r   r   likelihood_ratioraw_freqnltk.corpusr   r   r5   fileidsr   rp   r-   rH   rT   r`   printre   joinri   )scorercompare_scorerr   r   r   r   r   word_filterfilewordr5   cfcorrrX   r   s                 @r   demor   b  s3     ~$55,55.OOI.MDK!*1--*=>*=$*=>$//6
Q
[)#boof56boon=>
 	ddbhhvr.BC.BsSXXc].BCD">#:#:";2d4[IJ "> Ds   ,EE__main__)r   zBigramAssocMeasures.r   rq   )rp   r   r   )NN)rl   	itertoolsr   r   r   r   r   r   nltk.metrics.spearmanr   r   nltk.probabilityr	   	nltk.utilr
   r   rp   r   r   r   ri   sysevalargvr   
IndexErrorr   __all__r:   r   r   <module>r      s   2   J % d dN037 03fAT8 ATHR
 9 R
jKL z0,sxx{:;4sxx{BC 	     s$   &B% ?B2 %B/.B/2B<;B<