Skip to content

Ngrams¤

Tokenizes such that each token is an "ngram," or a set of n words in a row.

Ngrams pydantic-model ¤

Bases: BaseModel

Generate ngrams from a text.

Config:

  • default: validation_config

Fields:

Source code in lexos/tokenizer/ngrams.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
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
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
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
class Ngrams(BaseModel):
    """Generate ngrams from a text."""

    n: int = Field(
        default=2,
        description="The size of the ngrams.",
    )
    drop_ws: Optional[bool] = Field(
        default=True,
        description="Whether to drop whitespace from the ngrams.",
    )
    filter_digits: Optional[bool] = Field(
        default=False,
        description="If True, remove ngrams that contain any digits. Automatically sets filter_nums to False.",
    )
    filter_nums: Optional[bool] = Field(
        default=False,
        description="If True, remove ngrams that contain any numbers or number-like tokens.",
    )
    filter_punct: Optional[bool] = Field(
        default=True,
        description="Remove ngrams that contain any punctuation-only tokens.",
    )
    filter_stops: Optional[bool | list[str]] = Field(
        default=[],
        description="Remove ngrams that start or end with a stop word in the provided list.",
    )
    min_freq: Optional[int] = Field(
        default=1,
        description="Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.",
    )
    output: Optional[str] = Field(
        default="text",
        description="The output format. Can be 'text', 'spans', or 'tuples'.",
    )
    tokenizer: Optional[Callable] = Field(
        default=WhitespaceTokenizer,
        description="The tokenizer to use.",
    )

    model_config = validation_config

    @property
    def stopwords(self) -> bool | list[str] | None:
        """Get the list of stopwords."""
        return self.filter_stops

    @validate_call(config=validation_config)
    def _filter_tokens(
        self,
        tokens: list[str],
        drop_ws: bool = True,
        filter_digits: bool = False,
        filter_punct: bool = True,
        filter_stops: list[str] = [],
    ) -> Generator:
        """Apply filters to a list of tokens.

        Args:
            tokens (list[str]): The list of tokens.
            drop_ws (bool): Whether to drop whitespace from the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.

        Returns:
            Generator: A generator of filtered tokens.
        """
        if drop_ws:
            tokens = (t.strip() for t in tokens)
        if len(filter_stops) > 0:
            tokens = (t for t in tokens if t not in filter_stops)
        if filter_punct:
            tokens = (t for t in tokens if not re.match("\\W", t))
        if filter_digits:
            tokens = (t for t in tokens if not re.match("\\d", t))
        yield from tokens

    def _set_attributes(
        self, skip_set_attrs: bool = False, **kwargs: dict[str, Any]
    ) -> None:
        """Set the instance attributes based on keyword arguments.

        Args:
            skip_set_attrs (bool): Whether to skip setting the attributes.
            **kwargs (dict[str, Any]): The keyword arguments to set the attributes.
        """
        if not skip_set_attrs:
            for key, value in kwargs.items():
                if hasattr(self, key):
                    setattr(self, key, value)

    @validate_call(config=validation_config)
    def from_doc(
        self,
        doc: Doc,
        n: int = 2,
        filter_digits: Optional[bool] = False,
        filter_nums: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[bool] = False,
        output: Optional[str] = "text",
        min_freq: Optional[int] = 1,
        skip_set_attrs: Optional[bool] = False,
        **kwargs: Any,
    ) -> Generator:
        """Generate a list of ngrams from a Doc.

        Args:
            doc (Doc): The source Doc.
            n (int): The size of the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (bool): Remove ngrams that start or end with a stop word in the provided list.
            output (str): The output format. Can be 'text', 'spans', or 'tuples'.
            min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
            skip_set_attrs (bool): Whether to skip setting the attributes.
            **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

        Returns:
            Generator: A generator of ngrams.
        """
        attrs = {
            "n": n,
            "filter_digits": filter_digits,
            "filter_nums": filter_nums,
            "filter_punct": filter_punct,
            "filter_stops": filter_stops,
            "min_freq": min_freq,
            "output": output,
            "skip_set_attrs": skip_set_attrs,
        }
        attrs = {**attrs, **kwargs}
        self._set_attributes(**attrs)
        # Set filter_nums to false; we'll filter digits separately
        if filter_digits:
            self.filter_nums = False
        # Get the ngrams
        ngram_spans = textacy_ngrams(
            doc,
            n=self.n,
            filter_nums=self.filter_nums,
            filter_punct=self.filter_punct,
            filter_stops=self.filter_stops,
            **kwargs,
        )
        # Filter digits
        if filter_digits:
            ngram_spans = (
                ng for ng in ngram_spans if not any(token.is_digit for token in ng)
            )
        # Apply min_freq (for some reason, it doesn't work if passed to Textacy)
        if min_freq > 1:
            freqs = frequencies(ng.text.lower() for ng in ngram_spans)
            ngram_spans = (
                ng for ng in ngram_spans if freqs[ng.text.lower()] >= min_freq
            )
        # Yield the desired output
        if self.output == "text":
            for span in ngram_spans:
                yield span.text
        elif self.output == "spans":
            yield from ngram_spans
        elif self.output == "tuples":
            for span in ngram_spans:
                yield tuple([token.text for token in span])
        else:
            raise LexosException("Invalid output type.")

    @validate_call(config=validation_config)
    def from_docs(
        self,
        docs: Iterable[Doc],
        n: int = 2,
        filter_digits: Optional[bool] = False,
        filter_nums: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[bool] = False,
        min_freq: Optional[int] = 1,
        output: Optional[str] = "text",
        **kwargs: Any,
    ) -> list[Generator]:
        """Generate a list of ngrams from a Doc.

        Args:
            docs (Iterable[Doc]): An iterable of Docs.
            n (int): The size of the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
            min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
            output (str): The output format. Can be 'text', 'spans', or 'tuples'.
            **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

        Returns:
            list[Generator]: A list of ngram generators.
        """
        attrs = {
            "n": n,
            "filter_digits": filter_digits,
            "filter_nums": filter_nums,
            "filter_punct": filter_punct,
            "filter_stops": filter_stops,
            "min_freq": min_freq,
            "output": output,
        }
        attrs = {**attrs, **kwargs}
        self._set_attributes(**attrs)
        ngram_list = []
        for doc in docs:
            ngram_list.append(self.from_doc(doc, skip_set_attrs=True))
        return ngram_list

    @validate_call(config=validation_config)
    def from_text(
        self,
        text: str,
        n: int = 2,
        drop_ws: Optional[bool] = True,
        filter_digits: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[Iterable[str]] = [],
        min_freq: Optional[int] = 1,
        output: Optional[str] = "text",
        skip_set_attrs: Optional[bool] = False,
        tokenizer: Optional[Callable] = WhitespaceTokenizer(),
    ) -> Generator:
        """Generate a list of ngrams from a list of tokens.

        Args:
            text (str): The text to generate ngrams from.
            n (int): The size of the ngrams.
            drop_ws (bool): Whether to drop whitespace from the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
            min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
            output (str): The output format. Can be 'text' or 'tuples'.
            skip_set_attrs (bool): Whether to skip setting the attributes.
            tokenizer (Callable): The tokenizer to use.

        Returns:
            Generator: A generator of ngrams.
        """
        self._set_attributes(
            n=n,
            drop_ws=drop_ws,
            filter_digits=filter_digits,
            filter_punct=filter_punct,
            filter_stops=filter_stops,
            min_freq=min_freq,
            output=output,
            skip_set_attrs=skip_set_attrs,
        )
        tokens = tokenizer(text)
        # If the user tokenises with a spaCy pipeline, we need to extract the text
        if isinstance(tokens[0], Token):
            tokens = [token.text for token in tokens]
        tokens = list(
            self._filter_tokens(
                tokens,
                self.drop_ws,
                self.filter_digits,
                self.filter_punct,
                self.filter_stops,
            )
        )
        ngrams = zip(*[tokens[i:] for i in range(self.n)])
        if min_freq > 1:
            ngrams = list(ngrams)
            freqs = frequencies("".join(ng).lower() for ng in ngrams)
            ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
        if self.output == "text":
            for ngram in ngrams:
                yield " ".join(ngram)
        elif self.output == "tuples":
            yield from ngrams
        else:
            raise LexosException("Invalid output type.")

    @validate_call(config=validation_config)
    def from_texts(
        self,
        texts: Iterable[str],
        n: int = 2,
        drop_ws: Optional[bool] = True,
        filter_digits: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[Iterable[str]] = [],
        min_freq: Optional[int] = 1,
        output: Optional[str] = "text",
        tokenizer: Optional[Callable] = WhitespaceTokenizer,
    ) -> list[Generator]:
        """Generate a list of ngrams from a list of tokens.

        Args:
            texts (Iterable[str]): An iterable of texts.
            n (int): The size of the ngrams.
            drop_ws (bool): Whether to drop whitespace from the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
            min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
            output (str): The output format. Can be 'text' or 'tuples'.
            tokenizer (Callable): The tokenizer to use.

        Returns:
            list[Generator]: A list of ngram generators.
        """
        self._set_attributes(
            n=n,
            drop_ws=drop_ws,
            filter_punct=filter_punct,
            filter_stops=filter_stops,
            filter_digits=filter_digits,
            min_freq=min_freq,
            output=output,
            tokenizer=tokenizer,
        )
        ngram_list = []
        for text in texts:
            ngram_list.append(self.from_text(text, skip_set_attrs=True))
        return ngram_list

    @validate_call(config=validation_config)
    def from_tokens(
        self,
        tokens: Iterable[str],
        n: int = 2,
        drop_ws: Optional[bool] = True,
        filter_digits: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[Iterable[str]] = [],
        min_freq: Optional[int] = 1,
        output: Optional[str] = "text",
        skip_set_attrs: Optional[bool] = False,
    ) -> Generator:
        """Generate a ngrams from an iterable of tokens.

        Args:
            tokens (Iterable[str]): An iterable of tokens.
            n (int): The size of the ngrams.
            drop_ws (bool): Whether to drop whitespace from the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
            min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
            output (str): The output format. Can be 'text' or 'tuples'.
            skip_set_attrs (bool): Whether to skip setting the attributes.

        Returns:
            Generator: A generator of ngrams.
        """
        self._set_attributes(
            n=n,
            drop_ws=drop_ws,
            filter_digits=filter_digits,
            filter_punct=filter_punct,
            filter_stops=filter_stops,
            min_freq=min_freq,
            output=output,
            skip_set_attrs=skip_set_attrs,
        )

        tokens = list(
            self._filter_tokens(
                tokens,
                self.drop_ws,
                self.filter_digits,
                self.filter_punct,
                self.filter_stops,
            )
        )
        ngrams = zip(*[tokens[i:] for i in range(self.n)])
        if min_freq > 1:
            ngrams = list(ngrams)
            freqs = frequencies("".join(ng).lower() for ng in ngrams)
            ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
        if self.output == "text":
            ngrams = zip(*[tokens[i:] for i in range(self.n)])
            for ngram in ngrams:
                yield " ".join(ngram)
        elif self.output == "tuples":
            yield from ngrams
        else:
            raise LexosException("Invalid output type.")

    @validate_call(config=validation_config)
    def from_token_lists(
        self,
        token_lists: Iterable[Iterable[str]],
        n: int = 2,
        drop_ws: Optional[bool] = True,
        filter_digits: Optional[bool] = False,
        filter_punct: Optional[bool] = True,
        filter_stops: Optional[Iterable[str]] = [],
        min_freq: Optional[int] = 1,
        output: Optional[str] = "text",
    ) -> list[Generator]:
        """Generate a ngrams from an iterable of tokens.

        Args:
            token_lists (Iterable[Iterable[str]]): An iterable of token lists.
            n (int): The size of the ngrams.
            drop_ws (bool): Whether to drop whitespace from the ngrams.
            filter_digits (bool): If True, remove ngrams that contain any digits.
            filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
            filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
            min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
            output (str): The output format. Can be 'text' or 'tuples'.

        Returns:
            list[Generator]: A list of ngram generators.
        """
        self._set_attributes(
            n=n,
            drop_ws=drop_ws,
            filter_digits=filter_digits,
            filter_punct=filter_punct,
            filter_stops=filter_stops,
            min_freq=min_freq,
            output=output,
        )
        ngram_list = []
        for token_list in token_lists:
            ngram_list.append(self.from_tokens(token_list, skip_set_attrs=True))
        return ngram_list

drop_ws: Optional[bool] = True pydantic-field ¤

Whether to drop whitespace from the ngrams.

filter_digits: Optional[bool] = False pydantic-field ¤

If True, remove ngrams that contain any digits. Automatically sets filter_nums to False.

filter_nums: Optional[bool] = False pydantic-field ¤

If True, remove ngrams that contain any numbers or number-like tokens.

filter_punct: Optional[bool] = True pydantic-field ¤

Remove ngrams that contain any punctuation-only tokens.

filter_stops: Optional[bool | list[str]] = [] pydantic-field ¤

Remove ngrams that start or end with a stop word in the provided list.

min_freq: Optional[int] = 1 pydantic-field ¤

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

n: int = 2 pydantic-field ¤

The size of the ngrams.

output: Optional[str] = 'text' pydantic-field ¤

The output format. Can be 'text', 'spans', or 'tuples'.

stopwords: bool | list[str] | None property ¤

Get the list of stopwords.

tokenizer: Optional[Callable] = WhitespaceTokenizer pydantic-field ¤

The tokenizer to use.

from_doc(doc: Doc, n: int = 2, filter_digits: Optional[bool] = False, filter_nums: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[bool] = False, output: Optional[str] = 'text', min_freq: Optional[int] = 1, skip_set_attrs: Optional[bool] = False, **kwargs: Any) -> Generator ¤

Generate a list of ngrams from a Doc.

Parameters:

Name Type Description Default
doc Doc

The source Doc.

required
n int

The size of the ngrams.

2
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_nums bool

If True, remove ngrams that contain any numbers or number-like tokens.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops bool

Remove ngrams that start or end with a stop word in the provided list.

False
output str

The output format. Can be 'text', 'spans', or 'tuples'.

'text'
min_freq int

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

1
skip_set_attrs bool

Whether to skip setting the attributes.

False
**kwargs Any

Extra keyword arguments to pass to textacy.extract.basics.ngrams.

{}

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_doc(
    self,
    doc: Doc,
    n: int = 2,
    filter_digits: Optional[bool] = False,
    filter_nums: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[bool] = False,
    output: Optional[str] = "text",
    min_freq: Optional[int] = 1,
    skip_set_attrs: Optional[bool] = False,
    **kwargs: Any,
) -> Generator:
    """Generate a list of ngrams from a Doc.

    Args:
        doc (Doc): The source Doc.
        n (int): The size of the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (bool): Remove ngrams that start or end with a stop word in the provided list.
        output (str): The output format. Can be 'text', 'spans', or 'tuples'.
        min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
        skip_set_attrs (bool): Whether to skip setting the attributes.
        **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

    Returns:
        Generator: A generator of ngrams.
    """
    attrs = {
        "n": n,
        "filter_digits": filter_digits,
        "filter_nums": filter_nums,
        "filter_punct": filter_punct,
        "filter_stops": filter_stops,
        "min_freq": min_freq,
        "output": output,
        "skip_set_attrs": skip_set_attrs,
    }
    attrs = {**attrs, **kwargs}
    self._set_attributes(**attrs)
    # Set filter_nums to false; we'll filter digits separately
    if filter_digits:
        self.filter_nums = False
    # Get the ngrams
    ngram_spans = textacy_ngrams(
        doc,
        n=self.n,
        filter_nums=self.filter_nums,
        filter_punct=self.filter_punct,
        filter_stops=self.filter_stops,
        **kwargs,
    )
    # Filter digits
    if filter_digits:
        ngram_spans = (
            ng for ng in ngram_spans if not any(token.is_digit for token in ng)
        )
    # Apply min_freq (for some reason, it doesn't work if passed to Textacy)
    if min_freq > 1:
        freqs = frequencies(ng.text.lower() for ng in ngram_spans)
        ngram_spans = (
            ng for ng in ngram_spans if freqs[ng.text.lower()] >= min_freq
        )
    # Yield the desired output
    if self.output == "text":
        for span in ngram_spans:
            yield span.text
    elif self.output == "spans":
        yield from ngram_spans
    elif self.output == "tuples":
        for span in ngram_spans:
            yield tuple([token.text for token in span])
    else:
        raise LexosException("Invalid output type.")

from_docs(docs: Iterable[Doc], n: int = 2, filter_digits: Optional[bool] = False, filter_nums: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[bool] = False, min_freq: Optional[int] = 1, output: Optional[str] = 'text', **kwargs: Any) -> list[Generator] ¤

Generate a list of ngrams from a Doc.

Parameters:

Name Type Description Default
docs Iterable[Doc]

An iterable of Docs.

required
n int

The size of the ngrams.

2
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_nums bool

If True, remove ngrams that contain any numbers or number-like tokens.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

False
min_freq int

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

1
output str

The output format. Can be 'text', 'spans', or 'tuples'.

'text'
**kwargs Any

Extra keyword arguments to pass to textacy.extract.basics.ngrams.

{}

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_docs(
    self,
    docs: Iterable[Doc],
    n: int = 2,
    filter_digits: Optional[bool] = False,
    filter_nums: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[bool] = False,
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    **kwargs: Any,
) -> list[Generator]:
    """Generate a list of ngrams from a Doc.

    Args:
        docs (Iterable[Doc]): An iterable of Docs.
        n (int): The size of the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
        output (str): The output format. Can be 'text', 'spans', or 'tuples'.
        **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    attrs = {
        "n": n,
        "filter_digits": filter_digits,
        "filter_nums": filter_nums,
        "filter_punct": filter_punct,
        "filter_stops": filter_stops,
        "min_freq": min_freq,
        "output": output,
    }
    attrs = {**attrs, **kwargs}
    self._set_attributes(**attrs)
    ngram_list = []
    for doc in docs:
        ngram_list.append(self.from_doc(doc, skip_set_attrs=True))
    return ngram_list

from_text(text: str, n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', skip_set_attrs: Optional[bool] = False, tokenizer: Optional[Callable] = WhitespaceTokenizer()) -> Generator ¤

Generate a list of ngrams from a list of tokens.

Parameters:

Name Type Description Default
text str

The text to generate ngrams from.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops Iterable[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq Optional[int]

Remove ngrams that occur in text fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
skip_set_attrs bool

Whether to skip setting the attributes.

False
tokenizer Callable

The tokenizer to use.

WhitespaceTokenizer()

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_text(
    self,
    text: str,
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    skip_set_attrs: Optional[bool] = False,
    tokenizer: Optional[Callable] = WhitespaceTokenizer(),
) -> Generator:
    """Generate a list of ngrams from a list of tokens.

    Args:
        text (str): The text to generate ngrams from.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        skip_set_attrs (bool): Whether to skip setting the attributes.
        tokenizer (Callable): The tokenizer to use.

    Returns:
        Generator: A generator of ngrams.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
        skip_set_attrs=skip_set_attrs,
    )
    tokens = tokenizer(text)
    # If the user tokenises with a spaCy pipeline, we need to extract the text
    if isinstance(tokens[0], Token):
        tokens = [token.text for token in tokens]
    tokens = list(
        self._filter_tokens(
            tokens,
            self.drop_ws,
            self.filter_digits,
            self.filter_punct,
            self.filter_stops,
        )
    )
    ngrams = zip(*[tokens[i:] for i in range(self.n)])
    if min_freq > 1:
        ngrams = list(ngrams)
        freqs = frequencies("".join(ng).lower() for ng in ngrams)
        ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
    if self.output == "text":
        for ngram in ngrams:
            yield " ".join(ngram)
    elif self.output == "tuples":
        yield from ngrams
    else:
        raise LexosException("Invalid output type.")

from_texts(texts: Iterable[str], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', tokenizer: Optional[Callable] = WhitespaceTokenizer) -> list[Generator] ¤

Generate a list of ngrams from a list of tokens.

Parameters:

Name Type Description Default
texts Iterable[str]

An iterable of texts.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq Optional[int]

Remove ngrams that occur in text fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
tokenizer Callable

The tokenizer to use.

WhitespaceTokenizer

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_texts(
    self,
    texts: Iterable[str],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    tokenizer: Optional[Callable] = WhitespaceTokenizer,
) -> list[Generator]:
    """Generate a list of ngrams from a list of tokens.

    Args:
        texts (Iterable[str]): An iterable of texts.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        tokenizer (Callable): The tokenizer to use.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        filter_digits=filter_digits,
        min_freq=min_freq,
        output=output,
        tokenizer=tokenizer,
    )
    ngram_list = []
    for text in texts:
        ngram_list.append(self.from_text(text, skip_set_attrs=True))
    return ngram_list

from_token_lists(token_lists: Iterable[Iterable[str]], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text') -> list[Generator] ¤

Generate a ngrams from an iterable of tokens.

Parameters:

Name Type Description Default
token_lists Iterable[Iterable[str]]

An iterable of token lists.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq int

Remove ngrams that occur in tokens fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_token_lists(
    self,
    token_lists: Iterable[Iterable[str]],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
) -> list[Generator]:
    """Generate a ngrams from an iterable of tokens.

    Args:
        token_lists (Iterable[Iterable[str]]): An iterable of token lists.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
    )
    ngram_list = []
    for token_list in token_lists:
        ngram_list.append(self.from_tokens(token_list, skip_set_attrs=True))
    return ngram_list

from_tokens(tokens: Iterable[str], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', skip_set_attrs: Optional[bool] = False) -> Generator ¤

Generate a ngrams from an iterable of tokens.

Parameters:

Name Type Description Default
tokens Iterable[str]

An iterable of tokens.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops Iterable[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq int

Remove ngrams that occur in tokens fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
skip_set_attrs bool

Whether to skip setting the attributes.

False

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_tokens(
    self,
    tokens: Iterable[str],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    skip_set_attrs: Optional[bool] = False,
) -> Generator:
    """Generate a ngrams from an iterable of tokens.

    Args:
        tokens (Iterable[str]): An iterable of tokens.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        skip_set_attrs (bool): Whether to skip setting the attributes.

    Returns:
        Generator: A generator of ngrams.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
        skip_set_attrs=skip_set_attrs,
    )

    tokens = list(
        self._filter_tokens(
            tokens,
            self.drop_ws,
            self.filter_digits,
            self.filter_punct,
            self.filter_stops,
        )
    )
    ngrams = zip(*[tokens[i:] for i in range(self.n)])
    if min_freq > 1:
        ngrams = list(ngrams)
        freqs = frequencies("".join(ng).lower() for ng in ngrams)
        ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
    if self.output == "text":
        ngrams = zip(*[tokens[i:] for i in range(self.n)])
        for ngram in ngrams:
            yield " ".join(ngram)
    elif self.output == "tuples":
        yield from ngrams
    else:
        raise LexosException("Invalid output type.")

n: int = 2 pydantic-field ¤

The size of the ngrams.

drop_ws: Optional[bool] = True pydantic-field ¤

Whether to drop whitespace from the ngrams.

filter_digits: Optional[bool] = False pydantic-field ¤

If True, remove ngrams that contain any digits. Automatically sets filter_nums to False.

filter_nums: Optional[bool] = False pydantic-field ¤

If True, remove ngrams that contain any numbers or number-like tokens.

filter_punct: Optional[bool] = True pydantic-field ¤

Remove ngrams that contain any punctuation-only tokens.

filter_stops: Optional[bool | list[str]] = [] pydantic-field ¤

Remove ngrams that start or end with a stop word in the provided list.

min_freq: Optional[int] = 1 pydantic-field ¤

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

output: Optional[str] = 'text' pydantic-field ¤

The output format. Can be 'text', 'spans', or 'tuples'.

tokenizer: Optional[Callable] = WhitespaceTokenizer pydantic-field ¤

The tokenizer to use.

model_config = validation_config class-attribute instance-attribute ¤

stopwords: bool | list[str] | None property ¤

Get the list of stopwords.

_filter_tokens(tokens: list[str], drop_ws: bool = True, filter_digits: bool = False, filter_punct: bool = True, filter_stops: list[str] = []) -> Generator ¤

Apply filters to a list of tokens.

Parameters:

Name Type Description Default
tokens list[str]

The list of tokens.

required
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

[]

Returns:

Name Type Description
Generator Generator

A generator of filtered tokens.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def _filter_tokens(
    self,
    tokens: list[str],
    drop_ws: bool = True,
    filter_digits: bool = False,
    filter_punct: bool = True,
    filter_stops: list[str] = [],
) -> Generator:
    """Apply filters to a list of tokens.

    Args:
        tokens (list[str]): The list of tokens.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.

    Returns:
        Generator: A generator of filtered tokens.
    """
    if drop_ws:
        tokens = (t.strip() for t in tokens)
    if len(filter_stops) > 0:
        tokens = (t for t in tokens if t not in filter_stops)
    if filter_punct:
        tokens = (t for t in tokens if not re.match("\\W", t))
    if filter_digits:
        tokens = (t for t in tokens if not re.match("\\d", t))
    yield from tokens

_set_attributes(skip_set_attrs: bool = False, **kwargs: dict[str, Any]) -> None ¤

Set the instance attributes based on keyword arguments.

Parameters:

Name Type Description Default
skip_set_attrs bool

Whether to skip setting the attributes.

False
**kwargs dict[str, Any]

The keyword arguments to set the attributes.

{}
Source code in lexos/tokenizer/ngrams.py
def _set_attributes(
    self, skip_set_attrs: bool = False, **kwargs: dict[str, Any]
) -> None:
    """Set the instance attributes based on keyword arguments.

    Args:
        skip_set_attrs (bool): Whether to skip setting the attributes.
        **kwargs (dict[str, Any]): The keyword arguments to set the attributes.
    """
    if not skip_set_attrs:
        for key, value in kwargs.items():
            if hasattr(self, key):
                setattr(self, key, value)

from_doc(doc: Doc, n: int = 2, filter_digits: Optional[bool] = False, filter_nums: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[bool] = False, output: Optional[str] = 'text', min_freq: Optional[int] = 1, skip_set_attrs: Optional[bool] = False, **kwargs: Any) -> Generator ¤

Generate a list of ngrams from a Doc.

Parameters:

Name Type Description Default
doc Doc

The source Doc.

required
n int

The size of the ngrams.

2
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_nums bool

If True, remove ngrams that contain any numbers or number-like tokens.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops bool

Remove ngrams that start or end with a stop word in the provided list.

False
output str

The output format. Can be 'text', 'spans', or 'tuples'.

'text'
min_freq int

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

1
skip_set_attrs bool

Whether to skip setting the attributes.

False
**kwargs Any

Extra keyword arguments to pass to textacy.extract.basics.ngrams.

{}

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_doc(
    self,
    doc: Doc,
    n: int = 2,
    filter_digits: Optional[bool] = False,
    filter_nums: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[bool] = False,
    output: Optional[str] = "text",
    min_freq: Optional[int] = 1,
    skip_set_attrs: Optional[bool] = False,
    **kwargs: Any,
) -> Generator:
    """Generate a list of ngrams from a Doc.

    Args:
        doc (Doc): The source Doc.
        n (int): The size of the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (bool): Remove ngrams that start or end with a stop word in the provided list.
        output (str): The output format. Can be 'text', 'spans', or 'tuples'.
        min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
        skip_set_attrs (bool): Whether to skip setting the attributes.
        **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

    Returns:
        Generator: A generator of ngrams.
    """
    attrs = {
        "n": n,
        "filter_digits": filter_digits,
        "filter_nums": filter_nums,
        "filter_punct": filter_punct,
        "filter_stops": filter_stops,
        "min_freq": min_freq,
        "output": output,
        "skip_set_attrs": skip_set_attrs,
    }
    attrs = {**attrs, **kwargs}
    self._set_attributes(**attrs)
    # Set filter_nums to false; we'll filter digits separately
    if filter_digits:
        self.filter_nums = False
    # Get the ngrams
    ngram_spans = textacy_ngrams(
        doc,
        n=self.n,
        filter_nums=self.filter_nums,
        filter_punct=self.filter_punct,
        filter_stops=self.filter_stops,
        **kwargs,
    )
    # Filter digits
    if filter_digits:
        ngram_spans = (
            ng for ng in ngram_spans if not any(token.is_digit for token in ng)
        )
    # Apply min_freq (for some reason, it doesn't work if passed to Textacy)
    if min_freq > 1:
        freqs = frequencies(ng.text.lower() for ng in ngram_spans)
        ngram_spans = (
            ng for ng in ngram_spans if freqs[ng.text.lower()] >= min_freq
        )
    # Yield the desired output
    if self.output == "text":
        for span in ngram_spans:
            yield span.text
    elif self.output == "spans":
        yield from ngram_spans
    elif self.output == "tuples":
        for span in ngram_spans:
            yield tuple([token.text for token in span])
    else:
        raise LexosException("Invalid output type.")

from_docs(docs: Iterable[Doc], n: int = 2, filter_digits: Optional[bool] = False, filter_nums: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[bool] = False, min_freq: Optional[int] = 1, output: Optional[str] = 'text', **kwargs: Any) -> list[Generator] ¤

Generate a list of ngrams from a Doc.

Parameters:

Name Type Description Default
docs Iterable[Doc]

An iterable of Docs.

required
n int

The size of the ngrams.

2
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_nums bool

If True, remove ngrams that contain any numbers or number-like tokens.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

False
min_freq int

Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.

1
output str

The output format. Can be 'text', 'spans', or 'tuples'.

'text'
**kwargs Any

Extra keyword arguments to pass to textacy.extract.basics.ngrams.

{}

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_docs(
    self,
    docs: Iterable[Doc],
    n: int = 2,
    filter_digits: Optional[bool] = False,
    filter_nums: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[bool] = False,
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    **kwargs: Any,
) -> list[Generator]:
    """Generate a list of ngrams from a Doc.

    Args:
        docs (Iterable[Doc]): An iterable of Docs.
        n (int): The size of the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_nums (bool): If True, remove ngrams that contain any numbers or number-like tokens.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in text, doc, or tokens fewer than min_freq times.
        output (str): The output format. Can be 'text', 'spans', or 'tuples'.
        **kwargs (Any): Extra keyword arguments to pass to textacy.extract.basics.ngrams.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    attrs = {
        "n": n,
        "filter_digits": filter_digits,
        "filter_nums": filter_nums,
        "filter_punct": filter_punct,
        "filter_stops": filter_stops,
        "min_freq": min_freq,
        "output": output,
    }
    attrs = {**attrs, **kwargs}
    self._set_attributes(**attrs)
    ngram_list = []
    for doc in docs:
        ngram_list.append(self.from_doc(doc, skip_set_attrs=True))
    return ngram_list

from_text(text: str, n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', skip_set_attrs: Optional[bool] = False, tokenizer: Optional[Callable] = WhitespaceTokenizer()) -> Generator ¤

Generate a list of ngrams from a list of tokens.

Parameters:

Name Type Description Default
text str

The text to generate ngrams from.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops Iterable[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq Optional[int]

Remove ngrams that occur in text fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
skip_set_attrs bool

Whether to skip setting the attributes.

False
tokenizer Callable

The tokenizer to use.

WhitespaceTokenizer()

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_text(
    self,
    text: str,
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    skip_set_attrs: Optional[bool] = False,
    tokenizer: Optional[Callable] = WhitespaceTokenizer(),
) -> Generator:
    """Generate a list of ngrams from a list of tokens.

    Args:
        text (str): The text to generate ngrams from.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        skip_set_attrs (bool): Whether to skip setting the attributes.
        tokenizer (Callable): The tokenizer to use.

    Returns:
        Generator: A generator of ngrams.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
        skip_set_attrs=skip_set_attrs,
    )
    tokens = tokenizer(text)
    # If the user tokenises with a spaCy pipeline, we need to extract the text
    if isinstance(tokens[0], Token):
        tokens = [token.text for token in tokens]
    tokens = list(
        self._filter_tokens(
            tokens,
            self.drop_ws,
            self.filter_digits,
            self.filter_punct,
            self.filter_stops,
        )
    )
    ngrams = zip(*[tokens[i:] for i in range(self.n)])
    if min_freq > 1:
        ngrams = list(ngrams)
        freqs = frequencies("".join(ng).lower() for ng in ngrams)
        ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
    if self.output == "text":
        for ngram in ngrams:
            yield " ".join(ngram)
    elif self.output == "tuples":
        yield from ngrams
    else:
        raise LexosException("Invalid output type.")

from_texts(texts: Iterable[str], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', tokenizer: Optional[Callable] = WhitespaceTokenizer) -> list[Generator] ¤

Generate a list of ngrams from a list of tokens.

Parameters:

Name Type Description Default
texts Iterable[str]

An iterable of texts.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq Optional[int]

Remove ngrams that occur in text fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
tokenizer Callable

The tokenizer to use.

WhitespaceTokenizer

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_texts(
    self,
    texts: Iterable[str],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    tokenizer: Optional[Callable] = WhitespaceTokenizer,
) -> list[Generator]:
    """Generate a list of ngrams from a list of tokens.

    Args:
        texts (Iterable[str]): An iterable of texts.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (Optional[int]): Remove ngrams that occur in text fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        tokenizer (Callable): The tokenizer to use.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        filter_digits=filter_digits,
        min_freq=min_freq,
        output=output,
        tokenizer=tokenizer,
    )
    ngram_list = []
    for text in texts:
        ngram_list.append(self.from_text(text, skip_set_attrs=True))
    return ngram_list

from_tokens(tokens: Iterable[str], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text', skip_set_attrs: Optional[bool] = False) -> Generator ¤

Generate a ngrams from an iterable of tokens.

Parameters:

Name Type Description Default
tokens Iterable[str]

An iterable of tokens.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops Iterable[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq int

Remove ngrams that occur in tokens fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'
skip_set_attrs bool

Whether to skip setting the attributes.

False

Returns:

Name Type Description
Generator Generator

A generator of ngrams.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_tokens(
    self,
    tokens: Iterable[str],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
    skip_set_attrs: Optional[bool] = False,
) -> Generator:
    """Generate a ngrams from an iterable of tokens.

    Args:
        tokens (Iterable[str]): An iterable of tokens.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (Iterable[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.
        skip_set_attrs (bool): Whether to skip setting the attributes.

    Returns:
        Generator: A generator of ngrams.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
        skip_set_attrs=skip_set_attrs,
    )

    tokens = list(
        self._filter_tokens(
            tokens,
            self.drop_ws,
            self.filter_digits,
            self.filter_punct,
            self.filter_stops,
        )
    )
    ngrams = zip(*[tokens[i:] for i in range(self.n)])
    if min_freq > 1:
        ngrams = list(ngrams)
        freqs = frequencies("".join(ng).lower() for ng in ngrams)
        ngrams = (ng for ng in ngrams if freqs["".join(ng).lower()] >= min_freq)
    if self.output == "text":
        ngrams = zip(*[tokens[i:] for i in range(self.n)])
        for ngram in ngrams:
            yield " ".join(ngram)
    elif self.output == "tuples":
        yield from ngrams
    else:
        raise LexosException("Invalid output type.")

from_token_lists(token_lists: Iterable[Iterable[str]], n: int = 2, drop_ws: Optional[bool] = True, filter_digits: Optional[bool] = False, filter_punct: Optional[bool] = True, filter_stops: Optional[Iterable[str]] = [], min_freq: Optional[int] = 1, output: Optional[str] = 'text') -> list[Generator] ¤

Generate a ngrams from an iterable of tokens.

Parameters:

Name Type Description Default
token_lists Iterable[Iterable[str]]

An iterable of token lists.

required
n int

The size of the ngrams.

2
drop_ws bool

Whether to drop whitespace from the ngrams.

True
filter_digits bool

If True, remove ngrams that contain any digits.

False
filter_punct bool

Remove ngrams that contain any punctuation-only tokens.

True
filter_stops list[str]

Remove ngrams that start or end with a stop word in the provided list.

[]
min_freq int

Remove ngrams that occur in tokens fewer than min_freq times.

1
output str

The output format. Can be 'text' or 'tuples'.

'text'

Returns:

Type Description
list[Generator]

list[Generator]: A list of ngram generators.

Source code in lexos/tokenizer/ngrams.py
@validate_call(config=validation_config)
def from_token_lists(
    self,
    token_lists: Iterable[Iterable[str]],
    n: int = 2,
    drop_ws: Optional[bool] = True,
    filter_digits: Optional[bool] = False,
    filter_punct: Optional[bool] = True,
    filter_stops: Optional[Iterable[str]] = [],
    min_freq: Optional[int] = 1,
    output: Optional[str] = "text",
) -> list[Generator]:
    """Generate a ngrams from an iterable of tokens.

    Args:
        token_lists (Iterable[Iterable[str]]): An iterable of token lists.
        n (int): The size of the ngrams.
        drop_ws (bool): Whether to drop whitespace from the ngrams.
        filter_digits (bool): If True, remove ngrams that contain any digits.
        filter_punct (bool): Remove ngrams that contain any punctuation-only tokens.
        filter_stops (list[str]): Remove ngrams that start or end with a stop word in the provided list.
        min_freq (int): Remove ngrams that occur in tokens fewer than min_freq times.
        output (str): The output format. Can be 'text' or 'tuples'.

    Returns:
        list[Generator]: A list of ngram generators.
    """
    self._set_attributes(
        n=n,
        drop_ws=drop_ws,
        filter_digits=filter_digits,
        filter_punct=filter_punct,
        filter_stops=filter_stops,
        min_freq=min_freq,
        output=output,
    )
    ngram_list = []
    for token_list in token_lists:
        ngram_list.append(self.from_tokens(token_list, skip_set_attrs=True))
    return ngram_list