Skip to content

Utilities

ngrams

ngrams(
    n: int, in_expr: IntoExpr, as_str: bool = True
) -> pl.Expr

Gather each token together with the n - 1 tokens that follow it.

Parameters:

  • n (int) –

    Length of the n-gram: 1 for unigrams, 2 for bigrams, and so on.

  • in_expr (IntoExpr) –

    Column name or expression holding the tokens to gather.

  • as_str (bool, default: True ) –

    Join the tokens into one space-separated string. Set to False for a list column instead.

Returns:

  • Expr –

    Expression giving the n-gram starting at each row. The last n - 1 rows have no full n-gram to start and come out null, as does any n-gram covering a null token.

Notes

Rows are read in the order the frame holds them, so an n-gram will run from the end of one file into the start of the next. Add .over() on the file id column to stop them at the boundary:

>>> df.select(pl.col("token").corpus.ngrams(2).over("file_id"))

Source code in python/polars_corpus/utils.py
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def ngrams(n: int, in_expr: IntoExpr, as_str: bool = True) -> pl.Expr:
    """Gather each token together with the `n - 1` tokens that follow it.

    Parameters
    ----------
    n : int
        Length of the n-gram: 1 for unigrams, 2 for bigrams, and so on.
    in_expr : IntoExpr
        Column name or expression holding the tokens to gather.
    as_str : bool, default True
        Join the tokens into one space-separated string. Set to False for a
        list column instead.

    Returns
    -------
    pl.Expr
        Expression giving the n-gram starting at each row. The last `n - 1`
        rows have no full n-gram to start and come out null, as does any
        n-gram covering a null token.

    Notes
    -----
    Rows are read in the order the frame holds them, so an n-gram will run
    from the end of one file into the start of the next. Add `.over()` on the
    file id column to stop them at the boundary:

    ```>>> df.select(pl.col("token").corpus.ngrams(2).over("file_id"))```
    """
    if not isinstance(n, int) or n < 1:
        raise ValueError(f"n must be a positive integer, got {n!r}")

    expr = as_expr(in_expr)
    exprs = [expr.shift(-i) for i in range(n)]

    if as_str:
        # concat_str is null for the whole n-gram if any token in it is null.
        return pl.concat_str(exprs, separator=" ")
    # concat_list is not: a null token would leave a shorter n-gram behind
    # looking like a real one, so null those rows out to match.
    return (
        pl.when(pl.any_horizontal(sub.is_null() for sub in exprs))
        .then(None)
        .otherwise(pl.concat_list(exprs))
    )

proportion

proportion(
    in_expr: IntoExpr,
    in_group_by: Optional[IntoExpr] = None,
) -> pl.Expr

Rescale counts as a share of their total.

Parameters:

  • in_expr (IntoExpr) –

    Column name or expression holding the counts.

  • in_group_by (IntoExpr, default: None ) –

    Column name or expression to take the total within. By default the total is over the whole column.

Returns:

  • Expr –

    Expression giving each count divided by the total, so the values sum to 1.

Source code in python/polars_corpus/utils.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
def proportion(in_expr: IntoExpr, in_group_by: Optional[IntoExpr] = None) -> pl.Expr:
    """Rescale counts as a share of their total.

    Parameters
    ----------
    in_expr : IntoExpr
        Column name or expression holding the counts.
    in_group_by : IntoExpr, optional
        Column name or expression to take the total within. By default the
        total is over the whole column.

    Returns
    -------
    pl.Expr
        Expression giving each count divided by the total, so the values sum to 1.
    """
    expr = as_expr(in_expr)
    if in_group_by is None:
        return expr / expr.sum()
    else:
        group_by = as_expr(in_group_by)
        return expr / expr.sum().over(group_by)

is_letters

is_letters(
    in_expr: IntoExpr, allow_spaces: bool = False
) -> pl.Expr

Test whether each string is alphabetic.

Parameters:

  • in_expr (IntoExpr) –

    Column name or expression holding the strings to test.

  • allow_spaces (bool, default: False ) –

    Count a space as a letter, so multi-word strings such as n-grams pass.

Returns:

  • Expr –

    Boolean expression, true for a string holding at least one letter and nothing beyond letters, apostrophes and hyphens. False for anything else, the empty string included. A null stays null.

Notes

"Letter" is the Unicode category, so Greek, Cyrillic and Han count, as do accents written as a separate combining mark. Apostrophes (' or ’) and hyphens (as in don't or co-op) count as long as there is at least one letter in the string.

Source code in python/polars_corpus/utils.py
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
def is_letters(in_expr: IntoExpr, allow_spaces: bool = False) -> pl.Expr:
    """Test whether each string is alphabetic.

    Parameters
    ----------
    in_expr : IntoExpr
        Column name or expression holding the strings to test.
    allow_spaces : bool, default False
        Count a space as a letter, so multi-word strings such as n-grams pass.

    Returns
    -------
    pl.Expr
        Boolean expression, true for a string holding at least one letter and
        nothing beyond letters, apostrophes and hyphens. False for anything
        else, the empty string included. A null stays null.

    Notes
    -----
    "Letter" is the Unicode category, so Greek, Cyrillic and Han count, as do
    accents written as a separate combining mark. Apostrophes (`'` or `’`) and
    hyphens (as in *don't* or *co-op*) count as long as there is at least one
    letter in the string.
    """
    expr = as_expr(in_expr)
    others = "[-'’ ]" if allow_spaces else "[-'’]"
    return expr.str.contains(
        rf"\A{others}*(?:\p{{L}}\p{{M}}*)(?:{others}|\p{{L}}\p{{M}}*)*\z"
    )