Text helpers¶
Counting words and n-grams; see Build frequency distributions.
Text preprocessing helpers: n-gram generation and frequency counting.
These are convenience functions for the common (NLP) case where elements are tokens; the estimator core itself is domain-neutral.
generate_ngrams ¶
Generate n-grams from text.
A string input is treated as a sequence of characters, while a list input is treated as a sequence of tokens. Each n-gram is returned as a tuple.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str | list[str]
|
Input text, either a string (split into characters) or a list of tokens. |
required |
n
|
int
|
Size of the n-grams to generate. Must be positive. |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, ...]]
|
A list of n-gram tuples. Empty if the input has fewer than |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
Character n-grams from a string:
>>> from freqprob import generate_ngrams
>>> generate_ngrams("abcd", 2)
[('a', 'b'), ('b', 'c'), ('c', 'd')]
Token n-grams from a list:
word_frequency ¶
Compute word frequency from text.
A string input is split on whitespace into words; a list input is used as-is.
Counts are returned by default, or relative frequencies when normalize is
set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str | list[str]
|
Input text, either a whitespace-delimited string or a list of tokens. |
required |
normalize
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
dict[str, int | float]
|
A mapping of each word to its frequency (an |
dict[str, int | float]
|
relative frequency when |
Examples:
Raw counts:
>>> from freqprob import word_frequency
>>> word_frequency("hello world hello")
{'hello': 2, 'world': 1}
Normalized frequencies:
ngram_frequency ¶
ngram_frequency(text: str | list[str], n: int, normalize: bool = False) -> dict[tuple[str, ...], int | float]
Compute n-gram frequency from text.
Generates n-grams with generate_ngrams and counts them. Counts are
returned by default, or relative frequencies when normalize is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str | list[str]
|
Input text, either a string (split into characters) or a list of tokens. |
required |
n
|
int
|
Size of the n-grams to count. Must be positive. |
required |
normalize
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
dict[tuple[str, ...], int | float]
|
A mapping of each n-gram tuple to its frequency (an |
dict[tuple[str, ...], int | float]
|
|
Examples: