Skip to content

Lexical metrics

count_hapaxes

count_hapaxes(expr: IntoExpr) -> pl.Expr

Count the hapax legomena in a corpus.

A hapax legomenon is a type that occurs exactly once. Hapaxes are the first frequency class of the spectrum, V(1,N), and their share of the vocabulary is a common measure of productivity. Like ttr, this counts null as a type.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

Returns:

  • Expr –

    Expression returning the number of hapaxes as an integer scalar.

Source code in python/polars_corpus/lexical.py
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
def count_hapaxes(expr: IntoExpr) -> pl.Expr:
    """
    Count the hapax legomena in a corpus.

    A hapax legomenon is a type that occurs exactly once. Hapaxes are the
    first frequency class of the spectrum, `V(1,N)`, and their share of the
    vocabulary is a common measure of productivity. Like `ttr`, this counts
    null as a type.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.

    Returns
    -------
    pl.Expr
        Expression returning the number of hapaxes as an integer scalar.
    """
    return as_expr(expr).is_unique().sum()

frequency_spectrum

frequency_spectrum(
    expr: IntoExpr, sort: bool = False
) -> pl.Expr

Calculate the frequency spectrum of a corpus.

The frequency spectrum counts the types at each frequency: how many types occur once, how many occur twice, and so on.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

  • sort (bool, default: False ) –

    Sort the result by frequency class. Unsorted, the rows come back in whatever order value_counts produced, which differs from one evaluation of the same expression to the next.

Returns:

  • Expr –

    Expression returning one row per frequency class, as a struct with fields m (the frequency) and V(m,N) (the number of types that occur m times).

Source code in python/polars_corpus/lexical.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def frequency_spectrum(expr: IntoExpr, sort: bool = False) -> pl.Expr:
    """
    Calculate the frequency spectrum of a corpus.

    The frequency spectrum counts the types at each frequency: how many types
    occur once, how many occur twice, and so on.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.
    sort : bool, default=False
        Sort the result by frequency class. Unsorted, the rows come back in
        whatever order `value_counts` produced, which differs from one
        evaluation of the same expression to the next.

    Returns
    -------
    pl.Expr
        Expression returning one row per frequency class, as a struct with
        fields `m` (the frequency) and `V(m,N)` (the number of types that
        occur `m` times).
    """
    spectrum = (
        as_expr(expr)
        .value_counts(name="m", parallel=True)
        .struct.field("m")
        .value_counts(name="V(m,N)", parallel=True)
    )
    if sort:
        spectrum = spectrum.sort()
    return spectrum

msttr

msttr(expr: IntoExpr, n: int = 1000) -> pl.Expr

Calculate mean segmental type-token ratio (MSTTR).

MSTTR divides a text into consecutive non-overlapping segments of length n, calculates the TTR for each complete segment, and returns the mean of these values. Segments shorter than n tokens are dropped.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

  • n (int, default: 1000 ) –

    Segment size in tokens. Only complete segments of exactly this length are included in the calculation. Must be greater than 0.

Returns:

  • Expr –

    Expression returning the mean segmental TTR as a float scalar. Returns null if the text contains fewer than n tokens.

Raises:

  • ValueError –

    If n is not a positive integer.

  • TypeError –

    If n is not an integer.

Source code in python/polars_corpus/lexical.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def msttr(expr: IntoExpr, n: int = 1000) -> pl.Expr:
    """
    Calculate mean segmental type-token ratio (MSTTR).

    MSTTR divides a text into consecutive non-overlapping segments of length n,
    calculates the TTR for each complete segment, and returns the mean of these
    values. Segments shorter than n tokens are dropped.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.
    n : int, default=1000
        Segment size in tokens. Only complete segments of exactly this length
        are included in the calculation. Must be greater than 0.

    Returns
    -------
    pl.Expr
        Expression returning the mean segmental TTR as a float scalar.
        Returns null if the text contains fewer than n tokens.

    Raises
    ------
    ValueError
        If n is not a positive integer.
    TypeError
        If n is not an integer.
    """
    if not isinstance(n, int):
        raise TypeError(f"Segment size n must be an integer, got {type(n).__name__}")
    if n <= 0:
        raise ValueError(f"Segment size n must be greater than 0, got {n}")

    return register_plugin_function(
        plugin_path=LIB,
        args=[as_expr(expr)],
        function_name="py_msttr",
        is_elementwise=False,
        returns_scalar=True,
        kwargs={"n": n},
    )

mtld

mtld(expr: IntoExpr, threshold: float = 0.72) -> pl.Expr

Calculate Measure of Textual Lexical Diversity (MTLD).

MTLD (McCarthy & Jarvis, 2010) is a measure of lexical diversity that is relatively independent of text length. It works by counting "factors", i.e., sequential stretches of text where the type-token ratio (TTR) remains above a threshold. The measure is calculated in both forward and backward directions and the two values are averaged.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

  • threshold (float, default: 0.720 ) –

    TTR threshold for determining factor boundaries. The standard value is 0.720 (McCarthy & Jarvis, 2010). Must be strictly between 0 and 1.

Returns:

  • Expr –

    Expression returning the MTLD score as a float scalar, the mean number of tokens per factor. Higher values indicate greater lexical diversity. The score is null in two cases:

    • the text holds fewer than 10 tokens
    • the running TTR never falls to threshold, in one direction or the other, so that no factor closes

Raises:

  • ValueError –

    If threshold is not strictly between 0 and 1 (exclusive).

References
  • McCarthy, P. M. & Jarvis, S. 2010. MTLD, vocd-D, and HD-D: A validation study of sophisticated approaches to lexical diversity assessment. Behavior Research Methods 42(2): 381-392.
Source code in python/polars_corpus/lexical.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def mtld(expr: IntoExpr, threshold: float = 0.720) -> pl.Expr:
    """
    Calculate Measure of Textual Lexical Diversity (MTLD).

    MTLD (McCarthy & Jarvis, 2010) is a measure of lexical diversity that is
    relatively independent of text length. It works by counting "factors", i.e.,
    sequential stretches of text where the type-token ratio (TTR) remains above
    a threshold. The measure is calculated in both forward and backward
    directions and the two values are averaged.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.
    threshold : float, default=0.720
        TTR threshold for determining factor boundaries. The standard value
        is 0.720 (McCarthy & Jarvis, 2010). Must be strictly between 0 and 1.

    Returns
    -------
    pl.Expr
        Expression returning the MTLD score as a float scalar, the mean number
        of tokens per factor. Higher values indicate greater lexical diversity.
        The score is null in two cases:

        - the text holds fewer than 10 tokens
        - the running TTR never falls to `threshold`, in one direction or the
          other, so that no factor closes

    Raises
    ------
    ValueError
        If threshold is not strictly between 0 and 1 (exclusive).

    References
    ----------
    - McCarthy, P. M. & Jarvis, S. 2010. MTLD, vocd-D, and HD-D: A validation
      study of sophisticated approaches to lexical diversity assessment.
      *Behavior Research Methods* 42(2): 381-392.
    """
    if not 0 < threshold < 1:
        raise ValueError(
            f"Threshold must be strictly between 0 and 1 (exclusive), got {threshold}"
        )

    return register_plugin_function(
        plugin_path=LIB,
        args=[as_expr(expr)],
        function_name="py_mtld",
        is_elementwise=False,
        returns_scalar=True,
        kwargs={"threshold": threshold},
    )

ttr

ttr(expr: IntoExpr) -> pl.Expr

Calculate type-token ratio (TTR).

The type-token ratio is the ratio of unique tokens (types) to total tokens. TTR ranges from 0 to 1, with higher values indicating greater lexical diversity.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

Returns:

  • Expr –

    Expression returning the type-token ratio as a float scalar.

Source code in python/polars_corpus/lexical.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def ttr(expr: IntoExpr) -> pl.Expr:
    """
    Calculate type-token ratio (TTR).

    The type-token ratio is the ratio of unique tokens (types) to total tokens.
    TTR ranges from 0 to 1, with higher values indicating greater lexical diversity.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.

    Returns
    -------
    pl.Expr
        Expression returning the type-token ratio as a float scalar.
    """
    tokens = as_expr(expr)
    return tokens.n_unique() / tokens.len()

vocabulary_growth

vocabulary_growth(expr: IntoExpr) -> pl.Expr

Calculate a vocabulary growth curve V(N).

A vocabulary growth curve is the running count of types seen so far: the value in row N is the number of distinct tokens in the first N tokens of the corpus, so the last value equals the total number of types. Like ttr, this counts null as a type.

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

Returns:

  • Expr –

    Expression returning one type count per token, in corpus order.

References
  • Baayen, R. H. 1996, The effect of lexical specialization on the growth curve of the vocabulary. Computational Linguistics 22:455-480.
  • Baayen, R. H. 2001. Word Frequency Distributions. Kluwer Academic Publishers.
Source code in python/polars_corpus/lexical.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
def vocabulary_growth(expr: IntoExpr) -> pl.Expr:
    """
    Calculate a vocabulary growth curve V(N).

    A vocabulary growth curve is the running count of types seen so far: the
    value in row N is the number of distinct tokens in the first N tokens of
    the corpus, so the last value equals the total number of types. Like
    `ttr`, this counts null as a type.

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.

    Returns
    -------
    pl.Expr
        Expression returning one type count per token, in corpus order.

    References
    ----------
    - Baayen, R. H. 1996, The effect of lexical specialization on the growth curve
      of the vocabulary. *Computational Linguistics* 22:455-480.
    - Baayen, R. H. 2001. *Word Frequency Distributions.* Kluwer Academic Publishers.
    """
    return as_expr(expr).is_first_distinct().cum_sum()

yules_k

yules_k(expr: IntoExpr) -> pl.Expr

Calculate Yule's K characteristic.

Yule's K is a measure of lexical diversity that is relatively independent of text length. It is based on the frequency spectrum of word types, measuring how evenly vocabulary is distributed across frequency classes. Lower values indicate higher lexical diversity (more even distribution), while higher values indicate lower diversity (more repetition).

Parameters:

  • expr (IntoExpr) –

    Column name or expression holding the tokens to analyze.

Returns:

  • Expr –

    Expression returning Yule's K statistic as a float scalar. The value is scaled by 10,000 for readability.

References
  • Yule, G. U. 1944. The Statistical Study of Literary Vocabulary. Cambridge University Press.
Source code in python/polars_corpus/lexical.py
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
def yules_k(expr: IntoExpr) -> pl.Expr:
    """
    Calculate Yule's K characteristic.

    Yule's K is a measure of lexical diversity that is relatively independent
    of text length. It is based on the frequency spectrum of word types,
    measuring how evenly vocabulary is distributed across frequency classes.
    Lower values indicate higher lexical diversity (more even distribution),
    while higher values indicate lower diversity (more repetition).

    Parameters
    ----------
    expr : IntoExpr
        Column name or expression holding the tokens to analyze.

    Returns
    -------
    pl.Expr
        Expression returning Yule's K statistic as a float scalar.
        The value is scaled by 10,000 for readability.

    References
    ----------
    - Yule, G. U. 1944. *The Statistical Study of Literary Vocabulary.*
      Cambridge University Press.
    """
    tokens = as_expr(expr)
    n = tokens.len()
    # Sorted so that the two field extractions, which each re-evaluate the
    # spectrum, agree on row order; counts are cast to avoid u32 overflow.
    spectrum = frequency_spectrum(tokens, sort=True)
    m = spectrum.struct.field("m").cast(pl.Float64)
    v_m = spectrum.struct.field("V(m,N)").cast(pl.Float64)
    return 10000 * ((m.pow(2) * v_m / (n * n)).sum() - (1 / n))