Skip to content

Concordances

Examples: Concordances

search

search(
    df: DataFrame | LazyFrame,
    query: str,
    token_column: str = "token",
    pos_column: str = "pos",
    lemma_column: str = "lemma",
    file_id_column: Optional[str] = DEFAULT_FILE_ID,
    chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
) -> Optional[SearchResults | LazySearchResults]

Find every place in a corpus where a simple (BNCweb-style) query matches.

Parameters:

  • df (DataFrame | LazyFrame) –

    Corpus to search.

  • query (str) –

    Simple query, e.g. quick brown fox or {light}_V*. See Simple query language for the full syntax.

  • token_column (str, default: "token" ) –

    Column a bare word in the query is matched against.

  • pos_column (str, default: "pos" ) –

    Column the _TAG part of a query is matched against.

  • lemma_column (str, default: "lemma" ) –

    Column a {lemma} query is matched against.

  • file_id_column (str, default: DEFAULT_FILE_ID ) –

    Column holding file ids, which mark where one text ends and the next begins. No match crosses a change in its value. Pass None to search the corpus as one continuous run of tokens. A LazyFrame is searched a chunk of files at a time; without file ids to cut on it is searched as a single chunk.

  • chunk_tokens (int, default: 10_000_000 ) –

    Tokens to aim for per chunk when searching a LazyFrame by file. Lower it to use less memory, raise it for fewer passes over the corpus. Ignored for any other corpus, and for a LazyFrame with no file ids to cut chunks on.

Returns:

  • SearchResults or LazySearchResults or None –

    The matches, or None if the query matched nothing. A LazyFrame gives LazySearchResults and a DataFrame gives SearchResults.

Raises:

  • ValueError –

    If df is not a Polars DataFrame or LazyFrame or is missing file_id_column; if chunk_tokens is not a positive integer; or if query binds the same variable twice.

  • LarkError –

    If query is not a well-formed simple query.

  • ColumnNotFoundError –

    If the corpus has no column the query asks for -- a _TAG query against a corpus with no pos_column, say. Point the *_column arguments at the columns the corpus does have.

See Also

search_cqp : Search a corpus using a CQP query.

Examples:

>>> import polars_corpus as plc
>>> plc.search(corpus, "fox")
>>> plc.search(corpus, "quick brown fox")  # A sequence of words
>>> plc.search(corpus, "*ly_AJ0")  # Adjectives ending in "-ly"
>>> plc.search(corpus, "{eat} * up")  # Forms of "eat", then "up"
>>> # A query written over a differently annotated corpus:
>>> plc.search(corpus, "{light}_V*", lemma_column="headword", pos_column="c5")
>>> # $name: captures part of the match, for concordance() to column off:
>>> plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
Source code in python/polars_corpus/matcher.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def search(
    df: pl.DataFrame | pl.LazyFrame,
    query: str,
    token_column: str = "token",
    pos_column: str = "pos",
    lemma_column: str = "lemma",
    file_id_column: Optional[str] = DEFAULT_FILE_ID,
    chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
) -> Optional[SearchResults | LazySearchResults]:
    """
    Find every place in a corpus where a simple (BNCweb-style) query matches.

    Parameters
    ----------
    df : DataFrame | LazyFrame
        Corpus to search.
    query : str
        Simple query, e.g. `quick brown fox` or `{light}_V*`. See
        [Simple query language](simple_query.md) for the full syntax.
    token_column : str, default "token"
        Column a bare word in the query is matched against.
    pos_column : str, default "pos"
        Column the `_TAG` part of a query is matched against.
    lemma_column : str, default "lemma"
        Column a `{lemma}` query is matched against.
    file_id_column : str, optional
        Column holding file ids, which mark where one text ends and the next
        begins. No match crosses a change in its value. Pass `None` to search
        the corpus as one continuous run of tokens. A LazyFrame is searched a
        chunk of files at a time; without file ids to cut on it is searched as
        a single chunk.
    chunk_tokens : int, default 10_000_000
        Tokens to aim for per chunk when searching a LazyFrame by file. Lower
        it to use less memory, raise it for fewer passes over the corpus.
        Ignored for any other corpus, and for a LazyFrame with no file ids to
        cut chunks on.

    Returns
    -------
    SearchResults or LazySearchResults or None
        The matches, or None if the query matched nothing. A LazyFrame gives
        `LazySearchResults` and a DataFrame gives `SearchResults`.

    Raises
    ------
    ValueError
        If `df` is not a Polars DataFrame or LazyFrame or is missing
        `file_id_column`; if `chunk_tokens` is not a positive integer; or if
        `query` binds the same variable twice.
    lark.exceptions.LarkError
        If `query` is not a well-formed simple query.
    polars.exceptions.ColumnNotFoundError
        If the corpus has no column the query asks for -- a `_TAG` query
        against a corpus with no `pos_column`, say. Point the `*_column`
        arguments at the columns the corpus does have.

    See Also
    --------
    search_cqp : Search a corpus using a CQP query.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.search(corpus, "fox")
    >>> plc.search(corpus, "quick brown fox")  # A sequence of words
    >>> plc.search(corpus, "*ly_AJ0")  # Adjectives ending in "-ly"
    >>> plc.search(corpus, "{eat} * up")  # Forms of "eat", then "up"
    >>> # A query written over a differently annotated corpus:
    >>> plc.search(corpus, "{light}_V*", lemma_column="headword", pos_column="c5")
    >>> # $name: captures part of the match, for concordance() to column off:
    >>> plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
    """
    cqp_query = simple_to_cqp(query, token_column, pos_column, lemma_column)
    return _search(df, cqp_query, query, file_id_column, chunk_tokens)

search_cqp

search_cqp(
    df: DataFrame | LazyFrame,
    query: str,
    file_id_column: Optional[str] = DEFAULT_FILE_ID,
    chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
) -> Optional[SearchResults | LazySearchResults]

Find every place in a corpus where a CQP query matches.

Parameters:

  • df (DataFrame | LazyFrame) –

    Corpus to search.

  • query (str) –

    CQP query, e.g. [pos="NN.*"] [lemma="be"]. See CQP query language for the full syntax.

  • file_id_column (str, default: DEFAULT_FILE_ID ) –

    Column holding file ids, which mark where one text ends and the next begins. No match crosses a change in its value. Pass None to search the corpus as one continuous run of tokens. A LazyFrame is searched a chunk of files at a time; without file ids to cut it on it is searched as a single chunk.

  • chunk_tokens (int, default: 10_000_000 ) –

    Tokens to aim for per chunk when searching a LazyFrame by file. Lower it to use less memory, raise it for fewer passes over the corpus.

Returns:

  • SearchResults or LazySearchResults or None –

    The matches, or None if the query matched nothing. A LazyFrame gives LazySearchResults and a DataFrame gives SearchResults.

Raises:

  • ValueError –

    If df is not a Polars DataFrame or LazyFrame or is missing file_id_column; if chunk_tokens is not a positive integer; or if query binds the same variable twice.

  • LarkError –

    If query is not a well-formed CQP query.

  • ColumnNotFoundError –

    If the corpus has no column a constraint in query names.

See Also

search : Search a corpus using a simple query language.

Examples:

>>> import polars_corpus as plc
>>> plc.search_cqp(corpus, '[token="fox"%c]')  # %c to ignore case
>>> plc.search_cqp(corpus, '[pos="NN.*"]+ [pos="VB.*"]')  # Nouns, then a verb
>>> plc.search_cqp(corpus, '[pos!="NN.*"]')  # Anything but a noun
>>> # A column that the simple query shorthands cannot reach:
>>> plc.search_cqp(corpus, '[speaker="A" & lemma="think"]')
>>> # Capture part of the match; `$name:` takes a node or a parenthesized
>>> # group, and each one gets a concordance column of its own:
>>> plc.search_cqp(corpus, '$det: [pos="DT"] $adjs: ([pos="JJ"]+) [pos="NN"]')
>>> # Out of core, over a corpus too large to hold in memory:
>>> plc.search_cqp(pl.scan_parquet("bnc.parquet"), '[token="fox"%c]')
Source code in python/polars_corpus/matcher.py
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def search_cqp(
    df: pl.DataFrame | pl.LazyFrame,
    query: str,
    file_id_column: Optional[str] = DEFAULT_FILE_ID,
    chunk_tokens: int = DEFAULT_CHUNK_TOKENS,
) -> Optional[SearchResults | LazySearchResults]:
    """
    Find every place in a corpus where a CQP query matches.

    Parameters
    ----------
    df : DataFrame | LazyFrame
        Corpus to search.
    query : str
        CQP query, e.g. `[pos="NN.*"] [lemma="be"]`. See
        [CQP query language](cqp_query.md) for the full syntax.
    file_id_column : str, optional
        Column holding file ids, which mark where one text ends and the next
        begins. No match crosses a change in its value. Pass `None` to search
        the corpus as one continuous run of tokens. A LazyFrame is searched a
        chunk of files at a time; without file ids to cut it on it is searched as
        a single chunk.
    chunk_tokens : int, default 10_000_000
        Tokens to aim for per chunk when searching a LazyFrame by file. Lower
        it to use less memory, raise it for fewer passes over the corpus.

    Returns
    -------
    SearchResults or LazySearchResults or None
        The matches, or None if the query matched nothing. A LazyFrame gives
        `LazySearchResults` and a DataFrame gives `SearchResults`.

    Raises
    ------
    ValueError
        If `df` is not a Polars DataFrame or LazyFrame or is missing
        `file_id_column`; if `chunk_tokens` is not a positive integer; or if
        `query` binds the same variable twice.
    lark.exceptions.LarkError
        If `query` is not a well-formed CQP query.
    polars.exceptions.ColumnNotFoundError
        If the corpus has no column a constraint in `query` names.

    See Also
    --------
    search : Search a corpus using a simple query language.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> plc.search_cqp(corpus, '[token="fox"%c]')  # %c to ignore case
    >>> plc.search_cqp(corpus, '[pos="NN.*"]+ [pos="VB.*"]')  # Nouns, then a verb
    >>> plc.search_cqp(corpus, '[pos!="NN.*"]')  # Anything but a noun
    >>> # A column that the simple query shorthands cannot reach:
    >>> plc.search_cqp(corpus, '[speaker="A" & lemma="think"]')
    >>> # Capture part of the match; `$name:` takes a node or a parenthesized
    >>> # group, and each one gets a concordance column of its own:
    >>> plc.search_cqp(corpus, '$det: [pos="DT"] $adjs: ([pos="JJ"]+) [pos="NN"]')
    >>> # Out of core, over a corpus too large to hold in memory:
    >>> plc.search_cqp(pl.scan_parquet("bnc.parquet"), '[token="fox"%c]')
    """
    return _search(df, query, query, file_id_column, chunk_tokens)

SearchResults

Bases: _SearchResultsBase

The matches found by searching an in-memory corpus.

Returned by search and search_cqp when given a DataFrame; there is no reason to construct one directly. It holds the corpus, and for each match the span of tokens the query covered. The words themselves stay in the corpus and are read back out when a method needs them.

Use len() to count the matches, and concordance or collocates to turn them into a frame. head, tail and sample cut them down to a readable number, and shuffle reorders them; all four return results of this same kind, so they can be chained.

Parameters:

  • df (DataFrame) –

    Corpus the search ran over. It must be eager: the matches index into it by position, and every method here reads its rows.

  • query (str) –

    Query these results came from, shown in their repr.

  • matches (list of Match) –

    The matched spans, in corpus order, each with what it captured.

  • variables (list of str) –

    Names the query captured, in the order to show them.

  • file_id_column (str, default: None ) –

    Column holding file ids. When given, concordance context stops at a change in its value, as the matches themselves did during the search.

See Also

LazySearchResults : The same interface over a corpus stored as a LazyFrame

Examples:

>>> import polars_corpus as plc
>>> results = plc.search(corpus, "quick")
>>> results
SearchResults<'quick'; 1 match>
>>> len(results)
1
>>> results.concordance("token", window=3)
Source code in python/polars_corpus/search.py
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
class SearchResults(_SearchResultsBase):
    """
    The matches found by searching an in-memory corpus.

    Returned by `search` and `search_cqp` when given a DataFrame; there is no
    reason to construct one directly. It holds the corpus, and for each match
    the span of tokens the query covered. The words themselves stay in the
    corpus and are read back out when a method needs them.

    Use `len()` to count the matches, and `concordance` or `collocates` to
    turn them into a frame. `head`, `tail` and `sample` cut them down to a
    readable number, and `shuffle` reorders them; all four return results of
    this same kind, so they can be chained.

    Parameters
    ----------
    df : DataFrame
        Corpus the search ran over. It must be eager: the matches index into
        it by position, and every method here reads its rows.
    query : str
        Query these results came from, shown in their `repr`.
    matches : list of Match
        The matched spans, in corpus order, each with what it captured.
    variables : list of str
        Names the query captured, in the order to show them.
    file_id_column : str, optional
        Column holding file ids. When given, concordance context stops at a
        change in its value, as the matches themselves did during the search.

    See Also
    --------
    LazySearchResults : The same interface over a corpus stored as a LazyFrame

    Examples
    --------
    >>> import polars_corpus as plc
    >>> results = plc.search(corpus, "quick")
    >>> results
    SearchResults<'quick'; 1 match>
    >>> len(results)
    1
    >>> results.concordance("token", window=3)
    """

    def __init__(
        self,
        df: pl.DataFrame,
        query: str,
        matches: list[Match],
        variables: list[str],
        file_id_column: Optional[str] = None,
    ) -> None:
        self._df = as_eager(df)
        if file_id_column is not None:
            check_columns(self._df, [file_id_column], param="file_id_column")
        self._query = query
        self._matches = matches
        self._variables = variables
        self._file_id_column = file_id_column

    def __len__(self) -> int:
        """Number of matches found."""
        return len(self._matches)

    @property
    def matches(self) -> list[Match]:
        """The matched spans, in corpus order, each with the variables it bound.

        Positions index into the corpus the search ran over, so a match reads
        back as `corpus[m.span.start : m.span.end]`. `LazySearchResults` has
        no counterpart: it holds its matches as a frame of file-relative spans
        rather than materializing one object apiece.

        Examples
        --------
        >>> results = plc.search(corpus, '$noun: [pos="NN"]')
        >>> results.matches[0].span
        Span(3, 4)
        >>> results.matches[0].bindings["noun"]
        Span(3, 4)
        """
        return self._matches

    def _frame(self) -> pl.DataFrame:
        return self._df

    def _corpus_size(self) -> int:
        return self._df.height

    def _concordance(
        self,
        expr: IntoExprColumn | list[IntoExprColumn],
        window: int,
        chunk_column: Optional[str],
        metadata: Optional[list[str]],
        names: list[str],
    ) -> pl.DataFrame:
        file_ids = (
            None
            if self._file_id_column is None
            else self._df.get_column(self._file_id_column)
        )
        return _build_conc(
            self._df,
            self._matches,
            expr,
            window,
            chunk_column,
            metadata,
            names,
            file_ids,
        )

    def _take(self, indices: Sequence[int]) -> SearchResults:
        return SearchResults(
            self._df,
            self._query,
            [self._matches[i] for i in indices],
            self._variables,
            self._file_id_column,
        )

    def with_spans_as_chunks(self, name: str = "spans") -> pl.DataFrame:
        """
        Write the matches back onto the corpus as a column of BIO tags.

        The reverse of pulling the matches out of the corpus: this marks them
        where they sit. The first token of each match is tagged "B", the rest
        of it "I", and every token no match covers "O". The result is an
        ordinary column, so the matches can be counted, grouped or plotted
        alongside the rest of the corpus.

        Parameters
        ----------
        name : str, default "spans"
            Name for the tag column added to the corpus.

        Returns
        -------
        pl.DataFrame
            The corpus, one row per token as before, with the tag column
            added.

        See Also
        --------
        polars_corpus.with_chunk_index : Number the chunks such a column marks.

        Examples
        --------
        >>> tagged = results.with_spans_as_chunks()
        >>> # One "B" per match, so counting them counts matches per file:
        >>> tagged.group_by("file_id").agg((pl.col("spans") == "B").sum())
        """
        # Extract spans from matches for Rust function
        spans = [match.span for match in self._matches]
        return self._df.with_columns(
            spans_to_chunks(spans, self._df.height).alias(name)
        )

matches property

matches: list[Match]

The matched spans, in corpus order, each with the variables it bound.

Positions index into the corpus the search ran over, so a match reads back as corpus[m.span.start : m.span.end]. LazySearchResults has no counterpart: it holds its matches as a frame of file-relative spans rather than materializing one object apiece.

Examples:

>>> results = plc.search(corpus, '$noun: [pos="NN"]')
>>> results.matches[0].span
Span(3, 4)
>>> results.matches[0].bindings["noun"]
Span(3, 4)

variables property

variables: list[str]

Names the query's $name: bindings capture, in the order it binds them.

A binding the query can skip -- one under ?, or in an alternative not taken -- is named here all the same, and is null in the concordance for the matches that did not capture it.

Examples:

>>> results = plc.search(corpus, "$det: the $noun: _NN1")
>>> results.variables
['det', 'noun']

__len__

__len__() -> int

Number of matches found.

Source code in python/polars_corpus/search.py
860
861
862
def __len__(self) -> int:
    """Number of matches found."""
    return len(self._matches)

collocates

collocates(
    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.

Takes the window words on each side of every match and counts how often each word occurs across all of them. This is the same context concordance shows; the matched words themselves are not counted.

Each count comes with the three other frequencies an association measure needs, so the result can be passed straight to one to find the words that occur near the matches more often than their own corpus frequency would predict. See Association metrics.

Parameters:

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

    Column name or expression to read the collocates 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 a match. A pair takes that many to the left and to the right, so (0, 5) counts only what follows a match and (5, 0) only what precedes it. At least one side must reach a token. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, as concordance takes. The window then runs to the edges of the chunk holding the match rather than a fixed number of words; pass a sentence tag column to keep collocates within the sentence.

  • min_freq (int, default: 5 ) –

    Number of times a word must occur in the windows to be reported. Association measures are unstable for rare pairs, so the default drops them. 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 found in the windows, in no particular order:

    • collocate : the word
    • freqs : a struct of four counts, named as the association measures expect:

      • f12 : times the word fell in a window
      • f1 : number of window positions available
      • f2 : the word's frequency in the whole corpus
      • n : number of tokens in the corpus, counting only those expr reads a value from

Raises:

  • ValueError –

    If window reaches no token on either side, min_freq is negative, or expr names more than one column.

Notes

The struct has the same layout crosstab produces, so the association measures take it as it comes.

f1 counts the context tokens the windows actually held, so a window truncated at a file boundary contributes only what it reached.

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.

Examples:

>>> results.collocates("token")
>>> results.collocates("token", window=3, min_freq=10)
>>> results.collocates("token", window=(0, 5))  # Only what follows
>>> results.collocates("token", chunk_column="sentence_tag")
>>> # Rank the collocates by how strongly they attract the search term:
>>> collocs = results.collocates("token")
>>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik()).sort(
...     "ll", descending=True
... )
Source code in python/polars_corpus/search.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def collocates(
    self,
    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.

    Takes the `window` words on each side of every match and counts how
    often each word occurs across all of them. This is the same context
    `concordance` shows; the matched words themselves are not counted.

    Each count comes with the three other frequencies an association
    measure needs, so the result can be passed straight to one to find the
    words that occur near the matches more often than their own corpus
    frequency would predict. See [Association metrics](assoc.md).

    Parameters
    ----------
    expr : IntoExprColumn, default "token"
        Column name or expression to read the collocates 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 a match. A pair takes that many to
        the left and to the right, so `(0, 5)` counts only what follows a
        match and `(5, 0)` only what precedes it. At least one side must
        reach a token. Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, as `concordance` takes. The window then runs
        to the edges of the chunk holding the match rather than a fixed
        number of words; pass a sentence tag column to keep collocates
        within the sentence.
    min_freq : int, default 5
        Number of times a word must occur in the windows to be reported.
        Association measures are unstable for rare pairs, so the default
        drops them. 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 found in the windows, in no particular
        order:

        - `collocate` : the word
        - `freqs` : a struct of four counts, named as the association
          measures expect:

            - `f12` : times the word fell in a window
            - `f1` : number of window positions available
            - `f2` : the word's frequency in the whole corpus
            - `n` : number of tokens in the corpus, counting only those
              `expr` reads a value from

    Raises
    ------
    ValueError
        If `window` reaches no token on either side, `min_freq` is
        negative, or `expr` names more than one column.

    Notes
    -----
    The struct has the same layout `crosstab` produces, so the association
    measures take it as it comes.

    `f1` counts the context tokens the windows actually held, so a window
    truncated at a file boundary contributes only what it reached.

    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`.

    Examples
    --------
    >>> results.collocates("token")
    >>> results.collocates("token", window=3, min_freq=10)
    >>> results.collocates("token", window=(0, 5))  # Only what follows
    >>> results.collocates("token", chunk_column="sentence_tag")
    >>> # Rank the collocates by how strongly they attract the search term:
    >>> collocs = results.collocates("token")
    >>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik()).sort(
    ...     "ll", descending=True
    ... )
    """
    span = _window_span(window, chunk_column)
    _check_count(min_freq, "min_freq", " Use min_freq=0 to keep them all.")
    if isinstance(expr, (list, tuple)):
        raise ValueError(
            "expr must name a single column to collocate with, not a list of "
            "them; call collocates() once per column instead"
        )
    counts = self._collocate_counts(
        expr, output_name(expr), span, chunk_column=chunk_column
    )
    return (
        counts.filter(pl.col("f12") >= min_freq)
        .select("collocate", pl.struct("f12", "f1", "f2", "n").alias(freqs_name))
        .collect(engine="streaming")
    )

concordance

concordance(
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 0,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    bindings: bool | str | list[str] = True,
    as_str: bool = False,
) -> pl.DataFrame

Lay the matches out as a KWIC (keyword in context) concordance.

Returns one row per match. The matched words go in a column named after expr, the words before them in {expr}_left_context, and the words after them in {expr}_right_context. All three hold a list of tokens rather than a joined string, so they can be filtered and aggregated like any other list column.

Parameters:

  • expr (IntoExprColumn or list of IntoExprColumn, default: "token" ) –

    Column name or expression to read the concordance text from (e.g. token or lemma). Pass a list to get one set of columns per name, so that words and tags can be shown side by side.

  • window (int, default: 0 ) –

    Words of context to take on each side of a match. The default of 0 takes none, and the context columns are then left out. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, marking each chunk with "B" on its first token and "I" on the rest. Context then runs to the edges of the chunk holding the match instead of counting a fixed number of words: back to the "B" that opened the chunk, and forward to the last "I" before the next one. Pass a sentence tag column to get the whole sentence a match sits in. window is ignored.

  • metadata (str or list of str, default: None ) –

    Column(s) of the corpus to carry through to each row as ordinary values rather than lists, e.g. file_id or category. The value is read off the match's first token.

  • bindings (bool, str or list of str, default: True ) –

    Which of the query's $name: captures to give a column of their own. True takes all of them, which does nothing if the query captured none. False takes none. A name, or a list of names, takes just those. See variables for what a query captured.

  • as_str (bool, default: False ) –

    Join each list of words into one space-separated string, so that the match, its context and each binding come back as a String column. A column holding anything but a list of strings is left as it is, so a struct of token and tag stays a list.

Returns:

  • DataFrame –

    One row per match, in the order the results hold them. That is corpus order, unless sample or shuffle has reordered them. For each column expr names:

    • {column} : the matched words, as a list
    • {column}_left_context : the words before the match, left out when window is 0 and no chunk_column is given
    • {column}_right_context : the words after the match, left out under the same condition
    • {column}_{name} : the words captured by each $name:

    Each name in metadata adds one more column, holding a single value rather than a list.

    With as_str=True each of those list columns holds one space-separated string instead.

Raises:

  • ValueError –

    If window is negative; if the corpus is missing a column named in metadata or chunk_column, or chunk_column does not hold strings; or if bindings names something the query did not capture.

See Also

kwic : Read one position of these lines, to sort or group them by it.

Notes

Context stops at a file boundary when the results know their file_id_column, as results of a search that named one do. Without it context is taken from the corpus in the order it is held, so it will run from the end of one file into the start of the next.

A binding column holds an empty list where the variable matched no token, as an optional one can, and a null where the match went down a branch of the query that never bound it at all.

The list form is what kwic and the view widget read, so joining is the last step. Sorting needs the lists and writing a file needs the strings, so a sort followed by an export ends in a join as_str comes too early to supply:

import polars.selectors as cs

conc.sort(plc.kwic("L1")).with_columns(
    cs.by_dtype(pl.List(pl.String)).list.join(" ")
)

Examples:

>>> results.concordance("token", window=3)
>>> results.concordance("token")  # The matches on their own
>>> results.concordance(["token", "pos"], window=5)  # Words and tags
>>> # Whole sentences of context, labelled with where they came from:
>>> results.concordance(
...     "token", chunk_column="sentence_tag", metadata=["file_id", "category"]
... )
>>> # A column per capture: token_adj and token_noun
>>> results = plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
>>> results.concordance("token", window=5)
>>> results.concordance("token", bindings="adj")  # Just the one
>>> # One string per column, ready to write out:
>>> results.concordance("token", window=5, as_str=True).write_csv("hits.csv")
Source code in python/polars_corpus/search.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def concordance(
    self,
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 0,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    bindings: bool | str | list[str] = True,
    as_str: bool = False,
) -> pl.DataFrame:
    """
    Lay the matches out as a KWIC (keyword in context) concordance.

    Returns one row per match. The matched words go in a column named
    after `expr`, the words before them in `{expr}_left_context`, and the
    words after them in `{expr}_right_context`. All three hold a list of
    tokens rather than a joined string, so they can be filtered and
    aggregated like any other list column.

    Parameters
    ----------
    expr : IntoExprColumn or list of IntoExprColumn, default "token"
        Column name or expression to read the concordance text from
        (e.g. token or lemma). Pass a list to get one set of columns per
        name, so that words and tags can be shown side by side.
    window : int, default 0
        Words of context to take on each side of a match. The default of 0
        takes none, and the context columns are then left out. Ignored
        when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, marking each chunk with "B" on its first token
        and "I" on the rest. Context then runs to the edges of the chunk
        holding the match instead of counting a fixed number of words:
        back to the "B" that opened the chunk, and forward to the last "I"
        before the next one. Pass a sentence tag column to get the whole
        sentence a match sits in. `window` is ignored.
    metadata : str or list of str, optional
        Column(s) of the corpus to carry through to each row as ordinary
        values rather than lists, e.g. `file_id` or `category`. The value
        is read off the match's first token.
    bindings : bool, str or list of str, default True
        Which of the query's `$name:` captures to give a column of their
        own. True takes all of them, which does nothing if the query
        captured none. False takes none. A name, or a list of names, takes
        just those. See `variables` for what a query captured.
    as_str : bool, default False
        Join each list of words into one space-separated string, so that
        the match, its context and each binding come back as a String
        column. A column holding anything but a list of strings is left as
        it is, so a struct of token and tag stays a list.

    Returns
    -------
    pl.DataFrame
        One row per match, in the order the results hold them. That is
        corpus order, unless `sample` or `shuffle` has reordered them. For
        each column `expr` names:

        - `{column}` : the matched words, as a list
        - `{column}_left_context` : the words before the match, left out
          when `window` is 0 and no `chunk_column` is given
        - `{column}_right_context` : the words after the match, left out
          under the same condition
        - `{column}_{name}` : the words captured by each `$name:`

        Each name in `metadata` adds one more column, holding a single
        value rather than a list.

        With `as_str=True` each of those list columns holds one
        space-separated string instead.

    Raises
    ------
    ValueError
        If `window` is negative; if the corpus is missing a column named
        in `metadata` or `chunk_column`, or `chunk_column` does not hold
        strings; or if `bindings` names something the query did not
        capture.

    See Also
    --------
    kwic : Read one position of these lines, to sort or group them by it.

    Notes
    -----
    Context stops at a file boundary when the results know their
    `file_id_column`, as results of a search that named one do. Without it
    context is taken from the corpus in the order it is held, so it will
    run from the end of one file into the start of the next.

    A binding column holds an empty list where the variable matched no
    token, as an optional one can, and a null where the match went down a
    branch of the query that never bound it at all.

    The list form is what `kwic` and the `view` widget read, so joining is
    the last step. Sorting needs the lists and writing a file needs the
    strings, so a sort followed by an export ends in a join `as_str` comes
    too early to supply:

    ```python
    import polars.selectors as cs

    conc.sort(plc.kwic("L1")).with_columns(
        cs.by_dtype(pl.List(pl.String)).list.join(" ")
    )
    ```

    Examples
    --------
    >>> results.concordance("token", window=3)
    >>> results.concordance("token")  # The matches on their own
    >>> results.concordance(["token", "pos"], window=5)  # Words and tags
    >>> # Whole sentences of context, labelled with where they came from:
    >>> results.concordance(
    ...     "token", chunk_column="sentence_tag", metadata=["file_id", "category"]
    ... )

    >>> # A column per capture: token_adj and token_noun
    >>> results = plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
    >>> results.concordance("token", window=5)
    >>> results.concordance("token", bindings="adj")  # Just the one

    >>> # One string per column, ready to write out:
    >>> results.concordance("token", window=5, as_str=True).write_csv("hits.csv")
    """
    if bindings is True:
        names = list(self.variables)
    elif bindings is False:
        names = []
    else:
        names = _check_variables(bindings, self.variables)

    if isinstance(metadata, str):
        metadata = [metadata]
    if metadata is not None:
        check_columns(self._frame(), metadata, param="metadata")

    if chunk_column is not None:
        check_columns(self._frame(), [chunk_column], param="chunk_column")
        dtype = self._frame().lazy().collect_schema()[chunk_column]
        if dtype != pl.String and not isinstance(dtype, (pl.Categorical, pl.Enum)):
            raise ValueError(
                f"chunk_column must hold the chunk tags 'B', 'I' and 'O' as "
                f"strings, but {chunk_column!r} holds {dtype}"
            )
    else:
        window = _check_count(window, "window", " Use window=0 for no context.")

    conc = self._concordance(expr, window, chunk_column, metadata, names)
    if as_str:
        # Only a list of words has a join; a list of structs, as a
        # concordance of token and tag holds, passes through untouched.
        conc = conc.with_columns(cs.by_dtype(pl.List(pl.String)).list.join(" "))
    return conc

encode

encode(
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
) -> pl.DataFrame

Embed each match together with its context.

Builds a concordance, joins each line back into a single string, and encodes it with model, so that matches used in similar contexts get similar vectors.

Parameters:

  • model (SentenceTransformer) –

    Model used to encode the concordance lines.

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

    Column name or Polars expression holding the text to encode. It must name a single column.

  • window (int, default: 5 ) –

    Number of tokens of context on both sides of each match. Pass 0 to encode the matches on their own. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column name defining chunk boundaries, as in concordance. When given, context extends to the chunk holding the match.

  • metadata (str or list[str], default: None ) –

    Column name(s) from the source corpus to carry through to the result, e.g. file_id or category.

Returns:

  • DataFrame –

    One row per match, with the concordance line under the output name of expr, its embedding in a "vector" column of Array(Float32, dim), and a column for each name in metadata.

Examples:

>>> from sentence_transformers import SentenceTransformer
>>> model = SentenceTransformer("all-MiniLM-L6-v2")
>>> results.encode(model, window=10)
>>> results.encode(model, chunk_column="sentence_tag", metadata="file_id")
Source code in python/polars_corpus/search.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def encode(
    self,
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
) -> pl.DataFrame:
    """Embed each match together with its context.

    Builds a concordance, joins each line back into a single string, and
    encodes it with `model`, so that matches used in similar contexts get
    similar vectors.

    Parameters
    ----------
    model : SentenceTransformer
        Model used to encode the concordance lines.
    expr : IntoExprColumn, default "token"
        Column name or Polars expression holding the text to encode. It
        must name a single column.
    window : int, default 5
        Number of tokens of context on both sides of each match. Pass 0
        to encode the matches on their own. Ignored when chunk_column is
        given.
    chunk_column : str, optional
        Column name defining chunk boundaries, as in `concordance`. When
        given, context extends to the chunk holding the match.
    metadata : str or list[str], optional
        Column name(s) from the source corpus to carry through to the
        result, e.g. file_id or category.

    Returns
    -------
    pl.DataFrame
        One row per match, with the concordance line under the output name
        of `expr`, its embedding in a "vector" column of
        `Array(Float32, dim)`, and a column for each name in metadata.

    Examples
    --------
    >>> from sentence_transformers import SentenceTransformer
    >>> model = SentenceTransformer("all-MiniLM-L6-v2")
    >>> results.encode(model, window=10)
    >>> results.encode(model, chunk_column="sentence_tag", metadata="file_id")
    """
    from .embeddings import encode

    if isinstance(expr, (list, tuple)):
        raise ValueError(
            "expr must name a single column to encode, not a list of them; "
            "call encode() once per column instead"
        )
    name = output_name(expr)
    conc = self.concordance(
        expr,
        window=window,
        chunk_column=chunk_column,
        metadata=metadata,
        bindings=False,
    )
    parts = [
        column
        for column in (f"{name}_left_context", name, f"{name}_right_context")
        if column in conc.columns
    ]
    keep = [metadata] if isinstance(metadata, str) else list(metadata or [])
    return (
        conc.lazy()
        .select(pl.concat_list(parts).list.join(" ").alias(name), *keep)
        .with_columns(vector=encode(model, name))
        .collect()
    )

head

head(n: int) -> Self

Keep the first n matches, dropping the rest.

"First" in the order the results are currently in: corpus order as a search returns them, or the order sample or shuffle left them in.

Parameters:

  • n (int) –

    Matches to keep. Asking for more than there are keeps them all.

Returns:

  • Self –

    The same kind of results, cut down to those matches.

Raises:

  • ValueError –

    If n is negative.

Examples:

>>> results.head(10).concordance("token", window=5)
Source code in python/polars_corpus/search.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def head(self, n: int) -> Self:
    """
    Keep the first `n` matches, dropping the rest.

    "First" in the order the results are currently in: corpus order as a
    search returns them, or the order `sample` or `shuffle` left them in.

    Parameters
    ----------
    n : int
        Matches to keep. Asking for more than there are keeps them all.

    Returns
    -------
    Self
        The same kind of results, cut down to those matches.

    Raises
    ------
    ValueError
        If `n` is negative.

    Examples
    --------
    >>> results.head(10).concordance("token", window=5)
    """
    _check_count(n, "n")
    if n >= len(self):
        return self
    return self._take(range(n))

sample

sample(k: int, seed: Optional[int] = None) -> Self

Draw k of the matches at random, without replacement.

Useful when a query has more hits than can be read through. Every match is equally likely to be drawn, so the sample is not weighted toward the start of the corpus. The matches come back in the order drawn, not in corpus order.

Parameters:

  • k (int) –

    Matches to draw. Cannot be more than there are.

  • seed (int, default: None ) –

    Seed for the draw. Set it to get the same sample back every time the code is rerun, which is what reporting a result needs. Without one, the draw differs each run.

Returns:

  • Self –

    The same kind of results, holding the k matches drawn.

Raises:

  • ValueError –

    If k is negative or larger than the number of matches.

Notes

Seeding is local: the global random state is put back afterwards, so this does not disturb anything else in the notebook drawing at random.

Examples:

>>> # 100 hits to read through, the same 100 on every rerun:
>>> results.sample(100, seed=42).view()
Source code in python/polars_corpus/search.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def sample(self, k: int, seed: Optional[int] = None) -> Self:
    """
    Draw `k` of the matches at random, without replacement.

    Useful when a query has more hits than can be read through. Every
    match is equally likely to be drawn, so the sample is not weighted
    toward the start of the corpus. The matches come back in the order
    drawn, not in corpus order.

    Parameters
    ----------
    k : int
        Matches to draw. Cannot be more than there are.
    seed : int, optional
        Seed for the draw. Set it to get the same sample back every time
        the code is rerun, which is what reporting a result needs. Without
        one, the draw differs each run.

    Returns
    -------
    Self
        The same kind of results, holding the `k` matches drawn.

    Raises
    ------
    ValueError
        If `k` is negative or larger than the number of matches.

    Notes
    -----
    Seeding is local: the global random state is put back afterwards, so
    this does not disturb anything else in the notebook drawing at random.

    Examples
    --------
    >>> # 100 hits to read through, the same 100 on every rerun:
    >>> results.sample(100, seed=42).view()
    """
    _check_count(k, "k")
    if k > len(self):
        raise ValueError(
            f"cannot sample {k:,} of {len(self):,} matches; "
            f"k must be no larger than the number of matches"
        )
    state = random.getstate()
    random.seed(seed)
    try:
        return self._take(random.sample(range(len(self)), k))
    finally:
        random.setstate(state)

shuffle

shuffle(seed: Optional[int] = None) -> Self

Put the matches in random order, keeping all of them.

Parameters:

  • seed (int, default: None ) –

    Seed for the shuffle. Set it to get the same order back every time the code is rerun. Without one, the order differs each run.

Returns:

  • Self –

    The same kind of results, with the matches reordered.

Notes

Seeding is local: the global random state is put back afterwards, so this does not disturb anything else in the notebook drawing at random.

Examples:

>>> results.shuffle(seed=123).head(20)
Source code in python/polars_corpus/search.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def shuffle(self, seed: Optional[int] = None) -> Self:
    """
    Put the matches in random order, keeping all of them.

    Parameters
    ----------
    seed : int, optional
        Seed for the shuffle. Set it to get the same order back every time
        the code is rerun. Without one, the order differs each run.

    Returns
    -------
    Self
        The same kind of results, with the matches reordered.

    Notes
    -----
    Seeding is local: the global random state is put back afterwards, so
    this does not disturb anything else in the notebook drawing at random.

    Examples
    --------
    >>> results.shuffle(seed=123).head(20)
    """
    return self.sample(len(self), seed)

tail

tail(n: int) -> Self

Keep the last n matches, dropping the rest.

"Last" in the order the results are currently in: corpus order as a search returns them, or the order sample or shuffle left them in.

Parameters:

  • n (int) –

    Matches to keep. Asking for more than there are keeps them all.

Returns:

  • Self –

    The same kind of results, cut down to those matches.

Raises:

  • ValueError –

    If n is negative.

Examples:

>>> results.tail(10).concordance("token", window=5)
Source code in python/polars_corpus/search.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def tail(self, n: int) -> Self:
    """
    Keep the last `n` matches, dropping the rest.

    "Last" in the order the results are currently in: corpus order as a
    search returns them, or the order `sample` or `shuffle` left them in.

    Parameters
    ----------
    n : int
        Matches to keep. Asking for more than there are keeps them all.

    Returns
    -------
    Self
        The same kind of results, cut down to those matches.

    Raises
    ------
    ValueError
        If `n` is negative.

    Examples
    --------
    >>> results.tail(10).concordance("token", window=5)
    """
    _check_count(n, "n")
    if n >= len(self):
        return self
    return self._take(range(len(self) - n, len(self)))

view

view(
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    page_size: int = 25,
) -> None

Browse the concordance in a Jupyter notebook, a page at a time.

Builds the same lines concordance builds and displays them in a widget that pages, sorts and filters. Returns nothing; it draws in the notebook.

Parameters:

  • expr (IntoExprColumn or list of IntoExprColumn, default: "token" ) –

    Column name or expression to read the concordance text from (e.g. token or lemma). Where it names several, the first is the one shown.

  • window (int, default: 5 ) –

    Words of context to show on each side of a match. Pass 0 for none. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, to take context out to the edges of the chunk holding each match rather than by a fixed count, as in concordance.

  • metadata (str or list of str, default: None ) –

    Column(s) of the corpus to carry into the underlying concordance, e.g. file_id or category. The viewer draws only the match and its context, so these are not yet shown.

  • page_size (int, default: 25 ) –

    Concordance lines to draw per page.

See Also

concordance : The same lines as a DataFrame, to compute over.

Examples:

>>> results.view()
>>> results.view("token", window=10, page_size=50)
>>> # Whole sentences of context rather than a fixed window:
>>> results.view("token", chunk_column="sentence_tag")
Source code in python/polars_corpus/search.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def view(
    self,
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    page_size: int = 25,
) -> None:
    """
    Browse the concordance in a Jupyter notebook, a page at a time.

    Builds the same lines `concordance` builds and displays them in a
    widget that pages, sorts and filters. Returns nothing; it draws in the
    notebook.

    Parameters
    ----------
    expr : IntoExprColumn or list of IntoExprColumn, default "token"
        Column name or expression to read the concordance text from
        (e.g. token or lemma). Where it names several, the first is the
        one shown.
    window : int, default 5
        Words of context to show on each side of a match. Pass 0 for none.
        Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, to take context out to the edges of the chunk
        holding each match rather than by a fixed count, as in
        `concordance`.
    metadata : str or list of str, optional
        Column(s) of the corpus to carry into the underlying concordance,
        e.g. `file_id` or `category`. The viewer draws only the match and
        its context, so these are not yet shown.
    page_size : int, default 25
        Concordance lines to draw per page.

    See Also
    --------
    concordance : The same lines as a DataFrame, to compute over.

    Examples
    --------
    >>> results.view()
    >>> results.view("token", window=10, page_size=50)
    >>> # Whole sentences of context rather than a fixed window:
    >>> results.view("token", chunk_column="sentence_tag")
    """
    from .view import ConcordanceWidget

    conc = self.concordance(
        expr,
        window=window,
        chunk_column=chunk_column,
        metadata=metadata,
        bindings=False,
    )
    ConcordanceWidget(conc, page_size=page_size).show()

with_spans_as_chunks

with_spans_as_chunks(name: str = 'spans') -> pl.DataFrame

Write the matches back onto the corpus as a column of BIO tags.

The reverse of pulling the matches out of the corpus: this marks them where they sit. The first token of each match is tagged "B", the rest of it "I", and every token no match covers "O". The result is an ordinary column, so the matches can be counted, grouped or plotted alongside the rest of the corpus.

Parameters:

  • name (str, default: "spans" ) –

    Name for the tag column added to the corpus.

Returns:

  • DataFrame –

    The corpus, one row per token as before, with the tag column added.

See Also

polars_corpus.with_chunk_index : Number the chunks such a column marks.

Examples:

>>> tagged = results.with_spans_as_chunks()
>>> # One "B" per match, so counting them counts matches per file:
>>> tagged.group_by("file_id").agg((pl.col("spans") == "B").sum())
Source code in python/polars_corpus/search.py
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
def with_spans_as_chunks(self, name: str = "spans") -> pl.DataFrame:
    """
    Write the matches back onto the corpus as a column of BIO tags.

    The reverse of pulling the matches out of the corpus: this marks them
    where they sit. The first token of each match is tagged "B", the rest
    of it "I", and every token no match covers "O". The result is an
    ordinary column, so the matches can be counted, grouped or plotted
    alongside the rest of the corpus.

    Parameters
    ----------
    name : str, default "spans"
        Name for the tag column added to the corpus.

    Returns
    -------
    pl.DataFrame
        The corpus, one row per token as before, with the tag column
        added.

    See Also
    --------
    polars_corpus.with_chunk_index : Number the chunks such a column marks.

    Examples
    --------
    >>> tagged = results.with_spans_as_chunks()
    >>> # One "B" per match, so counting them counts matches per file:
    >>> tagged.group_by("file_id").agg((pl.col("spans") == "B").sum())
    """
    # Extract spans from matches for Rust function
    spans = [match.span for match in self._matches]
    return self._df.with_columns(
        spans_to_chunks(spans, self._df.height).alias(name)
    )

LazySearchResults

Bases: _SearchResultsBase

The matches found by searching an out-of-core corpus.

Returned by search and search_cqp when given a LazyFrame. It stores each match as an offset within the file the match falls in, and re-reads the corpus when a method needs the words. Each read covers only the part of a chunk that its matches fall in.

A corpus with no file ids is searched as a single file in a single chunk.

Parameters:

  • lf (LazyFrame) –

    Corpus the search ran over. Tokens sharing a file id must be contiguous, as the search itself already checked.

  • query (str) –

    Query these results came from, shown in their repr.

  • matches (DataFrame) –

    One row per match: start and end (token offsets within the file), _file (row index into files, which says where that file starts), and -- when the query captured variables -- a bindings struct column of per-variable file-relative spans.

  • variables (list of str) –

    Names the query captured, in the order it captures them.

  • file_id_column (str) –

    Column holding file ids.

  • files (DataFrame) –

    One row per file in corpus order: the file id column where there is one, _file, _len, _offset (global token offset) and _chunk (which chunk of the search held it).

See Also

SearchResults : The same interface over a corpus stored in a DataFrame.

Examples:

>>> import polars_corpus as plc
>>> results = plc.search(pl.scan_parquet("bnc.parquet"), "{eat} * up")
>>> results.concordance("token", window=5)
Source code in python/polars_corpus/search.py
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
class LazySearchResults(_SearchResultsBase):
    """
    The matches found by searching an out-of-core corpus.

    Returned by `search` and `search_cqp` when given a LazyFrame. It stores each
    match as an offset within the file the match falls in, and re-reads the
    corpus when a method needs the words. Each read covers only the part of a
    chunk that its matches fall in.

    A corpus with no file ids is searched as a single file in a single chunk.

    Parameters
    ----------
    lf : LazyFrame
        Corpus the search ran over. Tokens sharing a file id must be
        contiguous, as the search itself already checked.
    query : str
        Query these results came from, shown in their `repr`.
    matches : DataFrame
        One row per match: `start` and `end` (token offsets within the file),
        `_file` (row index into `files`, which says where that file starts),
        and -- when the query captured variables -- a `bindings` struct column
        of per-variable file-relative spans.
    variables : list of str
        Names the query captured, in the order it captures them.
    file_id_column : str, optional
        Column holding file ids.
    files : DataFrame
        One row per file in corpus order: the file id column where there is
        one, `_file`, `_len`, `_offset` (global token offset) and `_chunk`
        (which chunk of the search held it).

    See Also
    --------
    SearchResults : The same interface over a corpus stored in a DataFrame.

    Examples
    --------
    >>> import polars_corpus as plc
    >>> results = plc.search(pl.scan_parquet("bnc.parquet"), "{eat} * up")
    >>> results.concordance("token", window=5)
    """

    def __init__(
        self,
        lf: pl.LazyFrame,
        query: str,
        matches: pl.DataFrame,
        variables: list[str],
        file_id_column: Optional[str],
        files: pl.DataFrame,
    ) -> None:
        self._lf = lf
        self._query = query
        self._matches = matches
        self._variables = variables
        self._file_id_column = file_id_column
        self._files = files

    def __len__(self) -> int:
        """Number of matches found."""
        return self._matches.height

    def _frame(self) -> pl.LazyFrame:
        return self._lf

    def _corpus_size(self) -> int:
        return int(self._files["_len"].sum())

    def _concordance(
        self,
        expr: IntoExprColumn | list[IntoExprColumn],
        window: int,
        chunk_column: Optional[str],
        metadata: Optional[list[str]],
        names: list[str],
    ) -> pl.DataFrame:
        mf = self._matches.with_row_index("_order").join(
            self._files.select("_file", "_offset", "_len", "_chunk"),
            on="_file",
            how="left",
        )
        columns = _needed_columns(expr, metadata, chunk_column, self._file_id_column)

        parts: list[pl.DataFrame] = []
        orders: list[int] = []
        for _, group in mf.group_by("_chunk", maintain_order=True):
            # Only out to the files the chunk has matches in, which is no more
            # than the chunk and often much less.
            offset, end = group.select(
                pl.col("_offset").min().alias("start"),
                (pl.col("_offset") + pl.col("_len")).max().alias("end"),
            ).row(0)
            chunk_lf = self._lf.slice(offset, end - offset)
            if columns is not None:
                chunk_lf = chunk_lf.select(columns)
            chunk_df = chunk_lf.collect(engine="streaming")
            matches = _absolute_matches(group, offset)
            file_ids = (
                None
                if self._file_id_column is None
                else chunk_df.get_column(self._file_id_column)
            )
            parts.append(
                _build_conc(
                    chunk_df,
                    matches,
                    expr,
                    window,
                    chunk_column,
                    metadata,
                    names,
                    file_ids,
                )
            )
            orders.extend(group["_order"].to_list())

        return (
            pl.concat(parts)
            .with_columns(pl.Series("_order", orders, dtype=pl.UInt32))
            .sort("_order")
            .drop("_order")
        )

    def _take(self, indices: Sequence[int]) -> LazySearchResults:
        return LazySearchResults(
            self._lf,
            self._query,
            self._matches[list(indices)],
            self._variables,
            self._file_id_column,
            self._files,
        )

    def with_spans_as_chunks(self, name: str = "spans") -> pl.LazyFrame:
        """
        Write the matches back onto the corpus as BIO tags, lazily.

        The lazy counterpart of `SearchResults.with_spans_as_chunks`. It tags
        the corpus the same way: "B" on the first token of each match, "I" on
        the rest, "O" elsewhere. Returning a LazyFrame lets the corpus be
        filtered down to the matched tokens before anything is materialized.

        Parameters
        ----------
        name : str, default "spans"
            Name for the tag column added to the corpus.

        Returns
        -------
        pl.LazyFrame
            The corpus, one row per token as before, with the tag column
            added.

        Examples
        --------
        >>> # Just the matched tokens, without materializing the corpus:
        >>> results.with_spans_as_chunks().filter(pl.col("spans") != "O").collect()
        """
        start = pl.col("_offset").cast(pl.Int64) + pl.col("start")
        end = pl.col("_offset").cast(pl.Int64) + pl.col("end")
        tags = (
            self._matches.lazy()
            .join(self._files.lazy().select("_file", "_offset"), on="_file")
            .select(start.alias("_start"), pl.int_ranges(start, end).alias("_pos"))
            .explode("_pos", empty_as_null=False)
            .select(
                "_pos",
                pl.when(pl.col("_pos") == pl.col("_start"))
                .then(pl.lit("B"))
                .otherwise(pl.lit("I"))
                .alias(name),
            )
        )
        return (
            self._lf.drop(name, strict=False)
            .with_columns(pl.int_range(pl.len()).alias("_pos"))
            .join(tags, on="_pos", how="left", maintain_order="left")
            .with_columns(pl.col(name).fill_null("O"))
            .drop("_pos")
        )

variables property

variables: list[str]

Names the query's $name: bindings capture, in the order it binds them.

A binding the query can skip -- one under ?, or in an alternative not taken -- is named here all the same, and is null in the concordance for the matches that did not capture it.

Examples:

>>> results = plc.search(corpus, "$det: the $noun: _NN1")
>>> results.variables
['det', 'noun']

__len__

__len__() -> int

Number of matches found.

Source code in python/polars_corpus/search.py
1019
1020
1021
def __len__(self) -> int:
    """Number of matches found."""
    return self._matches.height

collocates

collocates(
    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.

Takes the window words on each side of every match and counts how often each word occurs across all of them. This is the same context concordance shows; the matched words themselves are not counted.

Each count comes with the three other frequencies an association measure needs, so the result can be passed straight to one to find the words that occur near the matches more often than their own corpus frequency would predict. See Association metrics.

Parameters:

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

    Column name or expression to read the collocates 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 a match. A pair takes that many to the left and to the right, so (0, 5) counts only what follows a match and (5, 0) only what precedes it. At least one side must reach a token. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, as concordance takes. The window then runs to the edges of the chunk holding the match rather than a fixed number of words; pass a sentence tag column to keep collocates within the sentence.

  • min_freq (int, default: 5 ) –

    Number of times a word must occur in the windows to be reported. Association measures are unstable for rare pairs, so the default drops them. 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 found in the windows, in no particular order:

    • collocate : the word
    • freqs : a struct of four counts, named as the association measures expect:

      • f12 : times the word fell in a window
      • f1 : number of window positions available
      • f2 : the word's frequency in the whole corpus
      • n : number of tokens in the corpus, counting only those expr reads a value from

Raises:

  • ValueError –

    If window reaches no token on either side, min_freq is negative, or expr names more than one column.

Notes

The struct has the same layout crosstab produces, so the association measures take it as it comes.

f1 counts the context tokens the windows actually held, so a window truncated at a file boundary contributes only what it reached.

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.

Examples:

>>> results.collocates("token")
>>> results.collocates("token", window=3, min_freq=10)
>>> results.collocates("token", window=(0, 5))  # Only what follows
>>> results.collocates("token", chunk_column="sentence_tag")
>>> # Rank the collocates by how strongly they attract the search term:
>>> collocs = results.collocates("token")
>>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik()).sort(
...     "ll", descending=True
... )
Source code in python/polars_corpus/search.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
def collocates(
    self,
    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.

    Takes the `window` words on each side of every match and counts how
    often each word occurs across all of them. This is the same context
    `concordance` shows; the matched words themselves are not counted.

    Each count comes with the three other frequencies an association
    measure needs, so the result can be passed straight to one to find the
    words that occur near the matches more often than their own corpus
    frequency would predict. See [Association metrics](assoc.md).

    Parameters
    ----------
    expr : IntoExprColumn, default "token"
        Column name or expression to read the collocates 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 a match. A pair takes that many to
        the left and to the right, so `(0, 5)` counts only what follows a
        match and `(5, 0)` only what precedes it. At least one side must
        reach a token. Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, as `concordance` takes. The window then runs
        to the edges of the chunk holding the match rather than a fixed
        number of words; pass a sentence tag column to keep collocates
        within the sentence.
    min_freq : int, default 5
        Number of times a word must occur in the windows to be reported.
        Association measures are unstable for rare pairs, so the default
        drops them. 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 found in the windows, in no particular
        order:

        - `collocate` : the word
        - `freqs` : a struct of four counts, named as the association
          measures expect:

            - `f12` : times the word fell in a window
            - `f1` : number of window positions available
            - `f2` : the word's frequency in the whole corpus
            - `n` : number of tokens in the corpus, counting only those
              `expr` reads a value from

    Raises
    ------
    ValueError
        If `window` reaches no token on either side, `min_freq` is
        negative, or `expr` names more than one column.

    Notes
    -----
    The struct has the same layout `crosstab` produces, so the association
    measures take it as it comes.

    `f1` counts the context tokens the windows actually held, so a window
    truncated at a file boundary contributes only what it reached.

    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`.

    Examples
    --------
    >>> results.collocates("token")
    >>> results.collocates("token", window=3, min_freq=10)
    >>> results.collocates("token", window=(0, 5))  # Only what follows
    >>> results.collocates("token", chunk_column="sentence_tag")
    >>> # Rank the collocates by how strongly they attract the search term:
    >>> collocs = results.collocates("token")
    >>> collocs.with_columns(ll=pl.col("freqs").corpus.loglik()).sort(
    ...     "ll", descending=True
    ... )
    """
    span = _window_span(window, chunk_column)
    _check_count(min_freq, "min_freq", " Use min_freq=0 to keep them all.")
    if isinstance(expr, (list, tuple)):
        raise ValueError(
            "expr must name a single column to collocate with, not a list of "
            "them; call collocates() once per column instead"
        )
    counts = self._collocate_counts(
        expr, output_name(expr), span, chunk_column=chunk_column
    )
    return (
        counts.filter(pl.col("f12") >= min_freq)
        .select("collocate", pl.struct("f12", "f1", "f2", "n").alias(freqs_name))
        .collect(engine="streaming")
    )

concordance

concordance(
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 0,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    bindings: bool | str | list[str] = True,
    as_str: bool = False,
) -> pl.DataFrame

Lay the matches out as a KWIC (keyword in context) concordance.

Returns one row per match. The matched words go in a column named after expr, the words before them in {expr}_left_context, and the words after them in {expr}_right_context. All three hold a list of tokens rather than a joined string, so they can be filtered and aggregated like any other list column.

Parameters:

  • expr (IntoExprColumn or list of IntoExprColumn, default: "token" ) –

    Column name or expression to read the concordance text from (e.g. token or lemma). Pass a list to get one set of columns per name, so that words and tags can be shown side by side.

  • window (int, default: 0 ) –

    Words of context to take on each side of a match. The default of 0 takes none, and the context columns are then left out. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, marking each chunk with "B" on its first token and "I" on the rest. Context then runs to the edges of the chunk holding the match instead of counting a fixed number of words: back to the "B" that opened the chunk, and forward to the last "I" before the next one. Pass a sentence tag column to get the whole sentence a match sits in. window is ignored.

  • metadata (str or list of str, default: None ) –

    Column(s) of the corpus to carry through to each row as ordinary values rather than lists, e.g. file_id or category. The value is read off the match's first token.

  • bindings (bool, str or list of str, default: True ) –

    Which of the query's $name: captures to give a column of their own. True takes all of them, which does nothing if the query captured none. False takes none. A name, or a list of names, takes just those. See variables for what a query captured.

  • as_str (bool, default: False ) –

    Join each list of words into one space-separated string, so that the match, its context and each binding come back as a String column. A column holding anything but a list of strings is left as it is, so a struct of token and tag stays a list.

Returns:

  • DataFrame –

    One row per match, in the order the results hold them. That is corpus order, unless sample or shuffle has reordered them. For each column expr names:

    • {column} : the matched words, as a list
    • {column}_left_context : the words before the match, left out when window is 0 and no chunk_column is given
    • {column}_right_context : the words after the match, left out under the same condition
    • {column}_{name} : the words captured by each $name:

    Each name in metadata adds one more column, holding a single value rather than a list.

    With as_str=True each of those list columns holds one space-separated string instead.

Raises:

  • ValueError –

    If window is negative; if the corpus is missing a column named in metadata or chunk_column, or chunk_column does not hold strings; or if bindings names something the query did not capture.

See Also

kwic : Read one position of these lines, to sort or group them by it.

Notes

Context stops at a file boundary when the results know their file_id_column, as results of a search that named one do. Without it context is taken from the corpus in the order it is held, so it will run from the end of one file into the start of the next.

A binding column holds an empty list where the variable matched no token, as an optional one can, and a null where the match went down a branch of the query that never bound it at all.

The list form is what kwic and the view widget read, so joining is the last step. Sorting needs the lists and writing a file needs the strings, so a sort followed by an export ends in a join as_str comes too early to supply:

import polars.selectors as cs

conc.sort(plc.kwic("L1")).with_columns(
    cs.by_dtype(pl.List(pl.String)).list.join(" ")
)

Examples:

>>> results.concordance("token", window=3)
>>> results.concordance("token")  # The matches on their own
>>> results.concordance(["token", "pos"], window=5)  # Words and tags
>>> # Whole sentences of context, labelled with where they came from:
>>> results.concordance(
...     "token", chunk_column="sentence_tag", metadata=["file_id", "category"]
... )
>>> # A column per capture: token_adj and token_noun
>>> results = plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
>>> results.concordance("token", window=5)
>>> results.concordance("token", bindings="adj")  # Just the one
>>> # One string per column, ready to write out:
>>> results.concordance("token", window=5, as_str=True).write_csv("hits.csv")
Source code in python/polars_corpus/search.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
def concordance(
    self,
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 0,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    bindings: bool | str | list[str] = True,
    as_str: bool = False,
) -> pl.DataFrame:
    """
    Lay the matches out as a KWIC (keyword in context) concordance.

    Returns one row per match. The matched words go in a column named
    after `expr`, the words before them in `{expr}_left_context`, and the
    words after them in `{expr}_right_context`. All three hold a list of
    tokens rather than a joined string, so they can be filtered and
    aggregated like any other list column.

    Parameters
    ----------
    expr : IntoExprColumn or list of IntoExprColumn, default "token"
        Column name or expression to read the concordance text from
        (e.g. token or lemma). Pass a list to get one set of columns per
        name, so that words and tags can be shown side by side.
    window : int, default 0
        Words of context to take on each side of a match. The default of 0
        takes none, and the context columns are then left out. Ignored
        when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, marking each chunk with "B" on its first token
        and "I" on the rest. Context then runs to the edges of the chunk
        holding the match instead of counting a fixed number of words:
        back to the "B" that opened the chunk, and forward to the last "I"
        before the next one. Pass a sentence tag column to get the whole
        sentence a match sits in. `window` is ignored.
    metadata : str or list of str, optional
        Column(s) of the corpus to carry through to each row as ordinary
        values rather than lists, e.g. `file_id` or `category`. The value
        is read off the match's first token.
    bindings : bool, str or list of str, default True
        Which of the query's `$name:` captures to give a column of their
        own. True takes all of them, which does nothing if the query
        captured none. False takes none. A name, or a list of names, takes
        just those. See `variables` for what a query captured.
    as_str : bool, default False
        Join each list of words into one space-separated string, so that
        the match, its context and each binding come back as a String
        column. A column holding anything but a list of strings is left as
        it is, so a struct of token and tag stays a list.

    Returns
    -------
    pl.DataFrame
        One row per match, in the order the results hold them. That is
        corpus order, unless `sample` or `shuffle` has reordered them. For
        each column `expr` names:

        - `{column}` : the matched words, as a list
        - `{column}_left_context` : the words before the match, left out
          when `window` is 0 and no `chunk_column` is given
        - `{column}_right_context` : the words after the match, left out
          under the same condition
        - `{column}_{name}` : the words captured by each `$name:`

        Each name in `metadata` adds one more column, holding a single
        value rather than a list.

        With `as_str=True` each of those list columns holds one
        space-separated string instead.

    Raises
    ------
    ValueError
        If `window` is negative; if the corpus is missing a column named
        in `metadata` or `chunk_column`, or `chunk_column` does not hold
        strings; or if `bindings` names something the query did not
        capture.

    See Also
    --------
    kwic : Read one position of these lines, to sort or group them by it.

    Notes
    -----
    Context stops at a file boundary when the results know their
    `file_id_column`, as results of a search that named one do. Without it
    context is taken from the corpus in the order it is held, so it will
    run from the end of one file into the start of the next.

    A binding column holds an empty list where the variable matched no
    token, as an optional one can, and a null where the match went down a
    branch of the query that never bound it at all.

    The list form is what `kwic` and the `view` widget read, so joining is
    the last step. Sorting needs the lists and writing a file needs the
    strings, so a sort followed by an export ends in a join `as_str` comes
    too early to supply:

    ```python
    import polars.selectors as cs

    conc.sort(plc.kwic("L1")).with_columns(
        cs.by_dtype(pl.List(pl.String)).list.join(" ")
    )
    ```

    Examples
    --------
    >>> results.concordance("token", window=3)
    >>> results.concordance("token")  # The matches on their own
    >>> results.concordance(["token", "pos"], window=5)  # Words and tags
    >>> # Whole sentences of context, labelled with where they came from:
    >>> results.concordance(
    ...     "token", chunk_column="sentence_tag", metadata=["file_id", "category"]
    ... )

    >>> # A column per capture: token_adj and token_noun
    >>> results = plc.search(corpus, "$adj: _AJ0 $noun: _NN1")
    >>> results.concordance("token", window=5)
    >>> results.concordance("token", bindings="adj")  # Just the one

    >>> # One string per column, ready to write out:
    >>> results.concordance("token", window=5, as_str=True).write_csv("hits.csv")
    """
    if bindings is True:
        names = list(self.variables)
    elif bindings is False:
        names = []
    else:
        names = _check_variables(bindings, self.variables)

    if isinstance(metadata, str):
        metadata = [metadata]
    if metadata is not None:
        check_columns(self._frame(), metadata, param="metadata")

    if chunk_column is not None:
        check_columns(self._frame(), [chunk_column], param="chunk_column")
        dtype = self._frame().lazy().collect_schema()[chunk_column]
        if dtype != pl.String and not isinstance(dtype, (pl.Categorical, pl.Enum)):
            raise ValueError(
                f"chunk_column must hold the chunk tags 'B', 'I' and 'O' as "
                f"strings, but {chunk_column!r} holds {dtype}"
            )
    else:
        window = _check_count(window, "window", " Use window=0 for no context.")

    conc = self._concordance(expr, window, chunk_column, metadata, names)
    if as_str:
        # Only a list of words has a join; a list of structs, as a
        # concordance of token and tag holds, passes through untouched.
        conc = conc.with_columns(cs.by_dtype(pl.List(pl.String)).list.join(" "))
    return conc

encode

encode(
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
) -> pl.DataFrame

Embed each match together with its context.

Builds a concordance, joins each line back into a single string, and encodes it with model, so that matches used in similar contexts get similar vectors.

Parameters:

  • model (SentenceTransformer) –

    Model used to encode the concordance lines.

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

    Column name or Polars expression holding the text to encode. It must name a single column.

  • window (int, default: 5 ) –

    Number of tokens of context on both sides of each match. Pass 0 to encode the matches on their own. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column name defining chunk boundaries, as in concordance. When given, context extends to the chunk holding the match.

  • metadata (str or list[str], default: None ) –

    Column name(s) from the source corpus to carry through to the result, e.g. file_id or category.

Returns:

  • DataFrame –

    One row per match, with the concordance line under the output name of expr, its embedding in a "vector" column of Array(Float32, dim), and a column for each name in metadata.

Examples:

>>> from sentence_transformers import SentenceTransformer
>>> model = SentenceTransformer("all-MiniLM-L6-v2")
>>> results.encode(model, window=10)
>>> results.encode(model, chunk_column="sentence_tag", metadata="file_id")
Source code in python/polars_corpus/search.py
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
def encode(
    self,
    model: SentenceTransformer,
    expr: IntoExprColumn = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
) -> pl.DataFrame:
    """Embed each match together with its context.

    Builds a concordance, joins each line back into a single string, and
    encodes it with `model`, so that matches used in similar contexts get
    similar vectors.

    Parameters
    ----------
    model : SentenceTransformer
        Model used to encode the concordance lines.
    expr : IntoExprColumn, default "token"
        Column name or Polars expression holding the text to encode. It
        must name a single column.
    window : int, default 5
        Number of tokens of context on both sides of each match. Pass 0
        to encode the matches on their own. Ignored when chunk_column is
        given.
    chunk_column : str, optional
        Column name defining chunk boundaries, as in `concordance`. When
        given, context extends to the chunk holding the match.
    metadata : str or list[str], optional
        Column name(s) from the source corpus to carry through to the
        result, e.g. file_id or category.

    Returns
    -------
    pl.DataFrame
        One row per match, with the concordance line under the output name
        of `expr`, its embedding in a "vector" column of
        `Array(Float32, dim)`, and a column for each name in metadata.

    Examples
    --------
    >>> from sentence_transformers import SentenceTransformer
    >>> model = SentenceTransformer("all-MiniLM-L6-v2")
    >>> results.encode(model, window=10)
    >>> results.encode(model, chunk_column="sentence_tag", metadata="file_id")
    """
    from .embeddings import encode

    if isinstance(expr, (list, tuple)):
        raise ValueError(
            "expr must name a single column to encode, not a list of them; "
            "call encode() once per column instead"
        )
    name = output_name(expr)
    conc = self.concordance(
        expr,
        window=window,
        chunk_column=chunk_column,
        metadata=metadata,
        bindings=False,
    )
    parts = [
        column
        for column in (f"{name}_left_context", name, f"{name}_right_context")
        if column in conc.columns
    ]
    keep = [metadata] if isinstance(metadata, str) else list(metadata or [])
    return (
        conc.lazy()
        .select(pl.concat_list(parts).list.join(" ").alias(name), *keep)
        .with_columns(vector=encode(model, name))
        .collect()
    )

head

head(n: int) -> Self

Keep the first n matches, dropping the rest.

"First" in the order the results are currently in: corpus order as a search returns them, or the order sample or shuffle left them in.

Parameters:

  • n (int) –

    Matches to keep. Asking for more than there are keeps them all.

Returns:

  • Self –

    The same kind of results, cut down to those matches.

Raises:

  • ValueError –

    If n is negative.

Examples:

>>> results.head(10).concordance("token", window=5)
Source code in python/polars_corpus/search.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
def head(self, n: int) -> Self:
    """
    Keep the first `n` matches, dropping the rest.

    "First" in the order the results are currently in: corpus order as a
    search returns them, or the order `sample` or `shuffle` left them in.

    Parameters
    ----------
    n : int
        Matches to keep. Asking for more than there are keeps them all.

    Returns
    -------
    Self
        The same kind of results, cut down to those matches.

    Raises
    ------
    ValueError
        If `n` is negative.

    Examples
    --------
    >>> results.head(10).concordance("token", window=5)
    """
    _check_count(n, "n")
    if n >= len(self):
        return self
    return self._take(range(n))

sample

sample(k: int, seed: Optional[int] = None) -> Self

Draw k of the matches at random, without replacement.

Useful when a query has more hits than can be read through. Every match is equally likely to be drawn, so the sample is not weighted toward the start of the corpus. The matches come back in the order drawn, not in corpus order.

Parameters:

  • k (int) –

    Matches to draw. Cannot be more than there are.

  • seed (int, default: None ) –

    Seed for the draw. Set it to get the same sample back every time the code is rerun, which is what reporting a result needs. Without one, the draw differs each run.

Returns:

  • Self –

    The same kind of results, holding the k matches drawn.

Raises:

  • ValueError –

    If k is negative or larger than the number of matches.

Notes

Seeding is local: the global random state is put back afterwards, so this does not disturb anything else in the notebook drawing at random.

Examples:

>>> # 100 hits to read through, the same 100 on every rerun:
>>> results.sample(100, seed=42).view()
Source code in python/polars_corpus/search.py
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def sample(self, k: int, seed: Optional[int] = None) -> Self:
    """
    Draw `k` of the matches at random, without replacement.

    Useful when a query has more hits than can be read through. Every
    match is equally likely to be drawn, so the sample is not weighted
    toward the start of the corpus. The matches come back in the order
    drawn, not in corpus order.

    Parameters
    ----------
    k : int
        Matches to draw. Cannot be more than there are.
    seed : int, optional
        Seed for the draw. Set it to get the same sample back every time
        the code is rerun, which is what reporting a result needs. Without
        one, the draw differs each run.

    Returns
    -------
    Self
        The same kind of results, holding the `k` matches drawn.

    Raises
    ------
    ValueError
        If `k` is negative or larger than the number of matches.

    Notes
    -----
    Seeding is local: the global random state is put back afterwards, so
    this does not disturb anything else in the notebook drawing at random.

    Examples
    --------
    >>> # 100 hits to read through, the same 100 on every rerun:
    >>> results.sample(100, seed=42).view()
    """
    _check_count(k, "k")
    if k > len(self):
        raise ValueError(
            f"cannot sample {k:,} of {len(self):,} matches; "
            f"k must be no larger than the number of matches"
        )
    state = random.getstate()
    random.seed(seed)
    try:
        return self._take(random.sample(range(len(self)), k))
    finally:
        random.setstate(state)

shuffle

shuffle(seed: Optional[int] = None) -> Self

Put the matches in random order, keeping all of them.

Parameters:

  • seed (int, default: None ) –

    Seed for the shuffle. Set it to get the same order back every time the code is rerun. Without one, the order differs each run.

Returns:

  • Self –

    The same kind of results, with the matches reordered.

Notes

Seeding is local: the global random state is put back afterwards, so this does not disturb anything else in the notebook drawing at random.

Examples:

>>> results.shuffle(seed=123).head(20)
Source code in python/polars_corpus/search.py
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def shuffle(self, seed: Optional[int] = None) -> Self:
    """
    Put the matches in random order, keeping all of them.

    Parameters
    ----------
    seed : int, optional
        Seed for the shuffle. Set it to get the same order back every time
        the code is rerun. Without one, the order differs each run.

    Returns
    -------
    Self
        The same kind of results, with the matches reordered.

    Notes
    -----
    Seeding is local: the global random state is put back afterwards, so
    this does not disturb anything else in the notebook drawing at random.

    Examples
    --------
    >>> results.shuffle(seed=123).head(20)
    """
    return self.sample(len(self), seed)

tail

tail(n: int) -> Self

Keep the last n matches, dropping the rest.

"Last" in the order the results are currently in: corpus order as a search returns them, or the order sample or shuffle left them in.

Parameters:

  • n (int) –

    Matches to keep. Asking for more than there are keeps them all.

Returns:

  • Self –

    The same kind of results, cut down to those matches.

Raises:

  • ValueError –

    If n is negative.

Examples:

>>> results.tail(10).concordance("token", window=5)
Source code in python/polars_corpus/search.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
def tail(self, n: int) -> Self:
    """
    Keep the last `n` matches, dropping the rest.

    "Last" in the order the results are currently in: corpus order as a
    search returns them, or the order `sample` or `shuffle` left them in.

    Parameters
    ----------
    n : int
        Matches to keep. Asking for more than there are keeps them all.

    Returns
    -------
    Self
        The same kind of results, cut down to those matches.

    Raises
    ------
    ValueError
        If `n` is negative.

    Examples
    --------
    >>> results.tail(10).concordance("token", window=5)
    """
    _check_count(n, "n")
    if n >= len(self):
        return self
    return self._take(range(len(self) - n, len(self)))

view

view(
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    page_size: int = 25,
) -> None

Browse the concordance in a Jupyter notebook, a page at a time.

Builds the same lines concordance builds and displays them in a widget that pages, sorts and filters. Returns nothing; it draws in the notebook.

Parameters:

  • expr (IntoExprColumn or list of IntoExprColumn, default: "token" ) –

    Column name or expression to read the concordance text from (e.g. token or lemma). Where it names several, the first is the one shown.

  • window (int, default: 5 ) –

    Words of context to show on each side of a match. Pass 0 for none. Ignored when chunk_column is given.

  • chunk_column (str, default: None ) –

    Column of BIO tags, to take context out to the edges of the chunk holding each match rather than by a fixed count, as in concordance.

  • metadata (str or list of str, default: None ) –

    Column(s) of the corpus to carry into the underlying concordance, e.g. file_id or category. The viewer draws only the match and its context, so these are not yet shown.

  • page_size (int, default: 25 ) –

    Concordance lines to draw per page.

See Also

concordance : The same lines as a DataFrame, to compute over.

Examples:

>>> results.view()
>>> results.view("token", window=10, page_size=50)
>>> # Whole sentences of context rather than a fixed window:
>>> results.view("token", chunk_column="sentence_tag")
Source code in python/polars_corpus/search.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
def view(
    self,
    expr: IntoExprColumn | list[IntoExprColumn] = "token",
    window: int = 5,
    chunk_column: Optional[str] = None,
    metadata: Optional[str | list[str]] = None,
    page_size: int = 25,
) -> None:
    """
    Browse the concordance in a Jupyter notebook, a page at a time.

    Builds the same lines `concordance` builds and displays them in a
    widget that pages, sorts and filters. Returns nothing; it draws in the
    notebook.

    Parameters
    ----------
    expr : IntoExprColumn or list of IntoExprColumn, default "token"
        Column name or expression to read the concordance text from
        (e.g. token or lemma). Where it names several, the first is the
        one shown.
    window : int, default 5
        Words of context to show on each side of a match. Pass 0 for none.
        Ignored when `chunk_column` is given.
    chunk_column : str, optional
        Column of BIO tags, to take context out to the edges of the chunk
        holding each match rather than by a fixed count, as in
        `concordance`.
    metadata : str or list of str, optional
        Column(s) of the corpus to carry into the underlying concordance,
        e.g. `file_id` or `category`. The viewer draws only the match and
        its context, so these are not yet shown.
    page_size : int, default 25
        Concordance lines to draw per page.

    See Also
    --------
    concordance : The same lines as a DataFrame, to compute over.

    Examples
    --------
    >>> results.view()
    >>> results.view("token", window=10, page_size=50)
    >>> # Whole sentences of context rather than a fixed window:
    >>> results.view("token", chunk_column="sentence_tag")
    """
    from .view import ConcordanceWidget

    conc = self.concordance(
        expr,
        window=window,
        chunk_column=chunk_column,
        metadata=metadata,
        bindings=False,
    )
    ConcordanceWidget(conc, page_size=page_size).show()

with_spans_as_chunks

with_spans_as_chunks(name: str = 'spans') -> pl.LazyFrame

Write the matches back onto the corpus as BIO tags, lazily.

The lazy counterpart of SearchResults.with_spans_as_chunks. It tags the corpus the same way: "B" on the first token of each match, "I" on the rest, "O" elsewhere. Returning a LazyFrame lets the corpus be filtered down to the matched tokens before anything is materialized.

Parameters:

  • name (str, default: "spans" ) –

    Name for the tag column added to the corpus.

Returns:

  • LazyFrame –

    The corpus, one row per token as before, with the tag column added.

Examples:

>>> # Just the matched tokens, without materializing the corpus:
>>> results.with_spans_as_chunks().filter(pl.col("spans") != "O").collect()
Source code in python/polars_corpus/search.py
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
def with_spans_as_chunks(self, name: str = "spans") -> pl.LazyFrame:
    """
    Write the matches back onto the corpus as BIO tags, lazily.

    The lazy counterpart of `SearchResults.with_spans_as_chunks`. It tags
    the corpus the same way: "B" on the first token of each match, "I" on
    the rest, "O" elsewhere. Returning a LazyFrame lets the corpus be
    filtered down to the matched tokens before anything is materialized.

    Parameters
    ----------
    name : str, default "spans"
        Name for the tag column added to the corpus.

    Returns
    -------
    pl.LazyFrame
        The corpus, one row per token as before, with the tag column
        added.

    Examples
    --------
    >>> # Just the matched tokens, without materializing the corpus:
    >>> results.with_spans_as_chunks().filter(pl.col("spans") != "O").collect()
    """
    start = pl.col("_offset").cast(pl.Int64) + pl.col("start")
    end = pl.col("_offset").cast(pl.Int64) + pl.col("end")
    tags = (
        self._matches.lazy()
        .join(self._files.lazy().select("_file", "_offset"), on="_file")
        .select(start.alias("_start"), pl.int_ranges(start, end).alias("_pos"))
        .explode("_pos", empty_as_null=False)
        .select(
            "_pos",
            pl.when(pl.col("_pos") == pl.col("_start"))
            .then(pl.lit("B"))
            .otherwise(pl.lit("I"))
            .alias(name),
        )
    )
    return (
        self._lf.drop(name, strict=False)
        .with_columns(pl.int_range(pl.len()).alias("_pos"))
        .join(tags, on="_pos", how="left", maintain_order="left")
        .with_columns(pl.col(name).fill_null("O"))
        .drop("_pos")
    )

kwic

kwic(position: str | int, column: str = 'token') -> pl.Expr

Read the word at one position of a concordance line.

"L1" is the word immediately before the match, "L2" the one before that, "R1" the word immediately after it, and "node" the match itself. Sorting and grouping a concordance is done by these positions, so this goes wherever a column would: sort, group_by, filter, select.

Parameters:

  • position (str or int) –

    Position to read: "L1", "L2", ... counting leftwards from the match, "R1", "R2", ... counting rightwards, or "node" for the match itself. Case does not matter, so "l1" works. An integer says the same thing the CQP way, negative to the left and positive to the right: -1 is "L1", 2 is "R2", and 0 is the node.

  • column (str, default: "token" ) –

    Column of the concordance holding the matched words, i.e. the column concordance was asked for. The context is read from {column}_left_context and {column}_right_context.

Returns:

  • Expr –

    Expression giving the word at that position as a string. A match of several tokens comes back as its words joined by spaces, so that it sorts as one string.

Raises:

  • ValueError –

    If position is not "L" or "R" followed by a number of 1 or more, "node", or the integer form of one of those.

See Also

SearchResults.concordance : The lines this reads a position out of.

Notes

A position the context does not reach comes out null: the window is shorter than the position asks for, or the context stopped at a file boundary. Pass nulls_last=True to sort to gather those lines at the end rather than the start.

Sorting is case-sensitive, so "The" sorts apart from "the". Fold the case where that is not wanted: plc.kwic("L1").str.to_lowercase().

kwic reads the list columns a concordance holds, so it is used before as_str=True, not after.

Examples:

>>> conc = results.concordance("token", window=5)
>>> conc.sort(plc.kwic("L1"), plc.kwic("L2"))  # The classic KWIC sort
>>> conc.group_by(plc.kwic("R1")).len()  # What follows the node
>>> conc.sort(plc.kwic("L1").str.to_lowercase(), nulls_last=True)
Source code in python/polars_corpus/search.py
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
def kwic(position: str | int, column: str = "token") -> pl.Expr:
    """
    Read the word at one position of a concordance line.

    `"L1"` is the word immediately before the match, `"L2"` the one before
    that, `"R1"` the word immediately after it, and `"node"` the match itself.
    Sorting and grouping a concordance is done by these positions, so this
    goes wherever a column would: `sort`, `group_by`, `filter`, `select`.

    Parameters
    ----------
    position : str or int
        Position to read: `"L1"`, `"L2"`, ... counting leftwards from the
        match, `"R1"`, `"R2"`, ... counting rightwards, or `"node"` for the
        match itself. Case does not matter, so `"l1"` works. An integer says
        the same thing the CQP way, negative to the left and positive to the
        right: -1 is `"L1"`, 2 is `"R2"`, and 0 is the node.
    column : str, default "token"
        Column of the concordance holding the matched words, i.e. the column
        `concordance` was asked for. The context is read from
        `{column}_left_context` and `{column}_right_context`.

    Returns
    -------
    pl.Expr
        Expression giving the word at that position as a string. A match of
        several tokens comes back as its words joined by spaces, so that it
        sorts as one string.

    Raises
    ------
    ValueError
        If `position` is not "L" or "R" followed by a number of 1 or more,
        "node", or the integer form of one of those.

    See Also
    --------
    SearchResults.concordance : The lines this reads a position out of.

    Notes
    -----
    A position the context does not reach comes out null: the window is
    shorter than the position asks for, or the context stopped at a file
    boundary. Pass `nulls_last=True` to `sort` to gather those lines at the
    end rather than the start.

    Sorting is case-sensitive, so "The" sorts apart from "the". Fold the case
    where that is not wanted: `plc.kwic("L1").str.to_lowercase()`.

    `kwic` reads the list columns a concordance holds, so it is used before
    `as_str=True`, not after.

    Examples
    --------
    >>> conc = results.concordance("token", window=5)
    >>> conc.sort(plc.kwic("L1"), plc.kwic("L2"))  # The classic KWIC sort
    >>> conc.group_by(plc.kwic("R1")).len()  # What follows the node
    >>> conc.sort(plc.kwic("L1").str.to_lowercase(), nulls_last=True)
    """
    side, n = "", 0
    if isinstance(position, int):
        if position == 0:
            side = "node"
        else:
            side, n = "R" if position > 0 else "L", abs(position)
    elif isinstance(position, str):
        text = position.strip().upper()
        if text == "NODE":
            side = "node"
        elif text[:1] in ("L", "R") and text[1:].isdecimal():
            side, n = text[0], int(text[1:])

    if side == "node":
        return pl.col(column).list.join(" ")
    if n >= 1:
        if side == "L":
            return pl.col(f"{column}_left_context").list.get(-n, null_on_oob=True)
        if side == "R":
            return pl.col(f"{column}_right_context").list.get(n - 1, null_on_oob=True)
    hint = (
        " Positions count from 1, so 'L1' is the word before the match." if side else ""
    )
    raise ValueError(
        f"position must be 'L1', 'L2', ... for a word before the match, "
        f"'R1', 'R2', ... for one after it, or 'node' for the match itself; "
        f"got {position!r}.{hint}"
    )