Skip to content

Collocation

collocations

collocations(
    results: SearchResults | LazySearchResults,
    expr: IntoExpr,
    method: str | Measure | list[str | Measure],
    window: int | tuple[int, int] = 5,
    chunk_column: Optional[str] = None,
    min_freq: int = 5,
    min_range: int = 0,
) -> pl.DataFrame

Rank the words that occur near a search's matches by strength of attraction.

Counts the words in a window around every match, the way collocates does, and scores each one against how often it occurs in the corpus at large. Words that the node word attracts occur in the windows more often than their own corpus frequency would predict, and come out at the top.

Parameters:

  • results (SearchResults or LazySearchResults) –

    Results of search or search_cqp.

  • expr (IntoExpr) –

    Column name or expression identifying the collocates (e.g. token or lemma). It must produce a single column, though that column may be a struct: pl.struct("lemma", "pos") collocates on the pair.

  • method (str | callable | list) –

    Association metric to rank the collocates by, or a list of them to compute together:

    • 'freq' : raw frequency in the windows, no association measure
    • 'pmi' : Pointwise Mutual Information, which favors rare words
    • 'mi3' : MI3, which pulls the ranking back towards frequent ones
    • 'logdice' : log-Dice, comparable across corpora of different sizes
    • 'll' : Log-likelihood ratio (G²)
    • 'chisq' : Pearson's chi-squared (χ²)
    • 'tscore' : t-score, which favors frequent words
    • 'zscore' : z-score
    • 'minsens' : Minimum sensitivity

    method can also be a Callable which takes the four counts f12, f1, f2 and n described under Returns. It receives them as Polars expressions and returns one expression.

  • window (int or (int, int), default: 5 ) –

    Words to take on each side of a match. To define an asymmetric window, pass a pair: (0, 5) collects only what follows a match and (5, 0) only what precedes it. At least one side must be > 0. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, as concordance takes. If provided, the window then runs to the edges of the chunk holding the match rather than a fixed number of words.

  • min_freq (int, default: 5 ) –

    Minimum number of times a word must occur in context to be reported.

  • min_range (int, default: 0 ) –

    Minimum number of distinct files a word must occur in in context to be reported.

Returns:

  • DataFrame –

    One row per collocate, sorted by the first measure asked for, strongest first:

    • collocate : the word, as expr reads it
    • freqs : a struct of the four counts the measures are computed from, laid out as crosstab lays them out -- f12 times the word fell in a window, f1 window positions filled, f2 the word's corpus frequency, n the corpus size
    • range : files the word collocated in, when the results know their file id column
    • one column per measure, in the order asked for

Raises:

  • ValueError –

    If results is None; if expr does not identify a single column of the corpus; if method is not one of the measures listed above, a function, or a list of them; if a measure of your own returns something that is not an expression, has no name to give its column, or names a column the result already holds; if window includes no context; or if min_range is asked for over results with no file id column.

See Also

search : Find the matches to collocate around. search_cqp : The same, from a CQP query. SearchResults.collocates : The window counts on their own, unranked. keywords : The same measures over two corpora rather than a window.

Notes

A word in the windows of two nearby matches is counted once for each, so overlapping windows count their shared words twice. A word's f12 can therefore come out higher than its corpus frequency f2.

The matched words themselves are never collocates of the match they belong to, but a second occurrence of the node word nearby is.

Examples:

>>> import polars_corpus as plc
>>> results = plc.search(corpus, "law")
>>> plc.collocations(results, "token", "logdice", window=3)
>>> # Several measures side by side, to see where they disagree:
>>> plc.collocations(results, "lemma", ["pmi", "tscore", "logdice"])
>>> # Colligation: the parts of speech a word keeps company with
>>> plc.collocations(results, "pos", "ll")
>>> # Lemma and tag together, so "spend_VERB" is its own collocate:
>>> plc.collocations(results, pl.struct("lemma", "pos"), "ll")
>>> # Only what follows the match, and only within its sentence:
>>> plc.collocations(results, "lemma", "ll", window=(0, 5))
>>> plc.collocations(results, "lemma", "ll", chunk_column="sentence_tag")
>>> # Drop collocations that come from just a handful of texts:
>>> plc.collocations(results, "lemma", "ll", min_freq=10, min_range=5)
>>> # A measure of your own, ranked beside one that ships:
>>> def jaccard(f12, f1, f2, n):
...     return f12 / (f1 + f2 - f12)
>>> plc.collocations(results, "lemma", ["ll", jaccard])
Source code in python/polars_corpus/collocations.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def collocations(
    results: SearchResults | LazySearchResults,
    expr: IntoExpr,
    method: str | Measure | list[str | Measure],
    window: int | tuple[int, int] = 5,
    chunk_column: Optional[str] = None,
    min_freq: int = 5,
    min_range: int = 0,
) -> pl.DataFrame:
    """
    Rank the words that occur near a search's matches by strength of attraction.

    Counts the words in a window around every match, the way `collocates`
    does, and scores each one against how often it occurs in the corpus at
    large. Words that the node word attracts occur in the windows
    more often than their own corpus frequency would predict, and come out at
    the top.

    Parameters
    ----------
    results : SearchResults or LazySearchResults
        Results of [`search`][polars_corpus.matcher.search] or
        [`search_cqp`][polars_corpus.matcher.search_cqp].
    expr : IntoExpr
        Column name or expression identifying the collocates (e.g. token or
        lemma). It must produce a single column, though that column may be a
        struct: `pl.struct("lemma", "pos")` collocates on the pair.
    method : str | callable | list
        [Association metric](assoc.md) to rank the collocates by, or a list of
        them to compute together:

        - 'freq' : raw frequency in the windows, no association measure
        - 'pmi' : Pointwise Mutual Information, which favors rare words
        - 'mi3' : MI3, which pulls the ranking back towards frequent ones
        - 'logdice' : log-Dice, comparable across corpora of different sizes
        - 'll' : Log-likelihood ratio (G²)
        - 'chisq' : Pearson's chi-squared (χ²)
        - 'tscore' : t-score, which favors frequent words
        - 'zscore' : z-score
        - 'minsens' : Minimum sensitivity

        `method` can also be a `Callable` which takes the four counts `f12`, `f1`, `f2`
         and `n` described under `Returns`. It receives them as Polars expressions
         and returns one expression.
    window : int or (int, int), default 5
        Words to take on each side of a match. To define an asymmetric window,
        pass a pair: `(0, 5)` collects only what follows a match and `(5, 0)` only what precedes it.
        At least one side must be > 0. Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, as `concordance` takes. If provided, the window then
        runs to  the edges of the chunk holding the match rather than a fixed number of
        words.
    min_freq : int, default 5
        Minimum number of times a word must occur in context to be reported.
    min_range : int, default 0
        Minimum number of distinct files a word must occur in in
        context to be reported.

    Returns
    -------
    pl.DataFrame
        One row per collocate, sorted by the first measure asked for,
        strongest first:

        - `collocate` : the word, as `expr` reads it
        - `freqs` : a struct of the four counts the measures are computed
          from, laid out as `crosstab` lays them out -- `f12` times the word
          fell in a window, `f1` window positions filled, `f2` the word's
          corpus frequency, `n` the corpus size
        - `range` : files the word collocated in, when the results know their
          file id column
        - one column per measure, in the order asked for

    Raises
    ------
    ValueError
        If `results` is None; if `expr` does not identify a single column of the
        corpus; if `method` is not one of the measures listed above, a function,
        or a list of them; if a measure of your own returns something that is
        not an expression, has no name to give its column, or names a column the
        result already holds; if `window` includes no context; or if `min_range`
        is asked for over results with no file id column.

    See Also
    --------
    [search][polars_corpus.matcher.search] : Find the matches to collocate around.
    [search_cqp][polars_corpus.matcher.search_cqp] : The same, from a CQP query.
    [SearchResults.collocates][polars_corpus.search.SearchResults.collocates] :
        The window counts on their own, unranked.
    [keywords][polars_corpus.keywords.keywords] :
        The same measures over two corpora rather than a window.

    Notes
    -----
    A word in the windows of two nearby matches is counted once for each, so
    overlapping windows count their shared words twice. A word's `f12` can
    therefore come out higher than its corpus frequency `f2`.

    The matched words themselves are never collocates of the match they
    belong to, but a second occurrence of the node word nearby is.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> results = plc.search(corpus, "law")
    >>> plc.collocations(results, "token", "logdice", window=3)
    >>> # Several measures side by side, to see where they disagree:
    >>> plc.collocations(results, "lemma", ["pmi", "tscore", "logdice"])
    >>> # Colligation: the parts of speech a word keeps company with
    >>> plc.collocations(results, "pos", "ll")
    >>> # Lemma and tag together, so "spend_VERB" is its own collocate:
    >>> plc.collocations(results, pl.struct("lemma", "pos"), "ll")
    >>> # Only what follows the match, and only within its sentence:
    >>> plc.collocations(results, "lemma", "ll", window=(0, 5))
    >>> plc.collocations(results, "lemma", "ll", chunk_column="sentence_tag")
    >>> # Drop collocations that come from just a handful of texts:
    >>> plc.collocations(results, "lemma", "ll", min_freq=10, min_range=5)
    >>> # A measure of your own, ranked beside one that ships:
    >>> def jaccard(f12, f1, f2, n):
    ...     return f12 / (f1 + f2 - f12)
    >>> plc.collocations(results, "lemma", ["ll", jaccard])
    """
    methods = check_measures(method, tuple(MEASURES))
    span = _window_span(window, chunk_column)
    _check_count(min_freq, "min_freq", " Use min_freq=0 to keep them all.")
    _check_count(min_range, "min_range")

    if results is None:
        raise ValueError(
            "collocations() needs the results of a search, but got None. A "
            "search that matched nothing returns None, and a node word with "
            "no matches has no windows to collect collocates from."
        )
    if not isinstance(results, (SearchResults, LazySearchResults)):
        raise ValueError(
            "results must be the matches search() or search_cqp() returned, "
            f"got {type(results).__name__}"
        )

    term = as_expr(expr)
    lf = results._frame().lazy()
    term_name = check_expr(lf, term)

    file_id_column = results._file_id_column
    if min_range and file_id_column is None:
        raise ValueError(
            "min_range counts the files a collocation occurs in, but these "
            "results have no file ids to count. Search with a "
            "file_id_column to get them."
        )

    result = results._collocate_counts(
        term, term_name, span, chunk_column, file_id_column
    )
    if min_freq:
        result = result.filter(pl.col("f12") >= min_freq)
    if min_range:
        result = result.filter(pl.col("range") >= min_range)

    # The built-ins are aliased in `MEASURES` and a measure of the caller's own
    # is aliased by `_apply_measure`, so each expression carries its own name.
    exprs = [
        MEASURES[m] if isinstance(m, str) else _apply_measure(m, *FREQS)
        for m in methods
    ]
    columns = [
        pl.col("collocate"),
        pl.struct(pl.col(FREQS).cast(pl.UInt64)).alias("freqs"),
    ]
    if file_id_column is not None:
        columns.append(pl.col("range"))
    columns += exprs

    names = [column.meta.output_name() for column in columns]
    taken = [name for name in names if names.count(name) > 1]
    if taken:
        raise ValueError(
            f"two columns of the result would be called {sorted(set(taken))[0]!r}. "
            "Alias the measure that names it, e.g. .alias('my_measure')"
        )

    result = result.select(*columns).sort(
        by=exprs[0].meta.output_name(), descending=True
    )

    return result.collect(engine="streaming")

collocates

collocates(
    search_results: SearchResults | LazySearchResults,
    expr: IntoExprColumn = "token",
    window: int | tuple[int, int] = 5,
    chunk_column: Optional[str] = None,
    min_freq: int = 5,
    freqs_name: str = "freqs",
) -> pl.DataFrame

Count the words that occur near the matches.

Parameters:

  • search_results (SearchResults or LazySearchResults) –

    Matches to collocate around, as search or search_cqp returned them.

  • expr (IntoExprColumn, default: "token" ) –

    Column name or expression the collocates are read from (e.g. token or lemma). It must name a single column.

  • window (int or (int, int), default: 5 ) –

    Words to take on each side of each match, or a (left, right) pair to take a different number on each. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags. The window then runs to the edges of the chunk holding the match rather than a fixed number of words.

  • min_freq (int, default: 5 ) –

    Times a word must occur in those windows to be reported. Pass 0 to keep them all.

  • freqs_name (str, default: "freqs" ) –

    Name for the struct column the counts come back in.

Returns:

  • DataFrame –

    One row per distinct word in the windows, with the four counts an association measure needs, laid out as SearchResults.collocates describes.

See Also

SearchResults.collocates : Method interface for the same functionality. collocations : The same counts, ranked by an association measure.

Examples:

>>> collocs = collocates(results, "token", window=3)
>>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik())
Source code in python/polars_corpus/search.py
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
def collocates(
    search_results: SearchResults | LazySearchResults,
    expr: IntoExprColumn = "token",
    window: int | tuple[int, int] = 5,
    chunk_column: Optional[str] = None,
    min_freq: int = 5,
    freqs_name: str = "freqs",
) -> pl.DataFrame:
    """
    Count the words that occur near the matches.

    Parameters
    ----------
    search_results : SearchResults or LazySearchResults
        Matches to collocate around, as `search` or `search_cqp` returned them.
    expr : IntoExprColumn, default "token"
        Column name or expression the collocates are read from (e.g. token or
        lemma). It must name a single column.
    window : int or (int, int), default 5
        Words to take on each side of each match, or a (left, right) pair to
        take a different number on each. Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags. The window then runs to the edges of the chunk
        holding the match rather than a fixed number of words.
    min_freq : int, default 5
        Times a word must occur in those windows to be reported. Pass 0 to
        keep them all.
    freqs_name : str, default "freqs"
        Name for the struct column the counts come back in.

    Returns
    -------
    pl.DataFrame
        One row per distinct word in the windows, with the four counts an
        association measure needs, laid out as `SearchResults.collocates`
        describes.

    See Also
    --------
    [SearchResults.collocates][polars_corpus.search.SearchResults.collocates] :
        Method interface for the same functionality.
    [collocations][polars_corpus.collocations.collocations] :
        The same counts, ranked by an association measure.

    Examples
    --------
    >>> collocs = collocates(results, "token", window=3)
    >>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik())
    """
    return search_results.collocates(expr, window, chunk_column, min_freq, freqs_name)