Algorithm Search⌘K

Algorithmcore

Punkt sentence tokenizer

Also called Kiss-Strunk sentence boundary detection.

Unsupervised sentence boundary detection of Kiss and Strunk. It finds abbreviations, initials and ordinal numbers by collocation statistics on raw text.

Time
O(n) expected
Space
O(n) extra
Where
n = the number of characters of the text
Properties
deterministicnot exactofflineiterative
Origin
Tibor Kiss, Jan Strunk, 2006

The Punkt sentence tokenizer of Kiss and Strunk (2006) decides which periods in a text end a sentence, and it learns everything it needs from raw text, with no labeled data and no word lists. It treats an abbreviation as a collocation of a word and its period: a type that almost always has a period, is short, and has internal periods is an abbreviation. A second pass looks at the word after each doubtful period and uses its capitalization, collocations and the list of frequent sentence starters. Punkt is one algorithm for sentence boundary detection; the problem page also covers supervised and rule-based methods.

In plain words

Most periods end a sentence. The hard cases are short words with a period, such as "Dr." or "etc.", initials such as "J.", and numbers such as "12." in a date.

Punkt first counts how often each word appears with a period and without one. A short word that nearly always has a period is taken as an abbreviation, and its period does not end the sentence.

Then it looks at the word after each doubtful period. If that word is capitalized but is normally written in lower case, a new sentence probably starts. If it is in lower case, the sentence goes on. If the pair of words, such as "J. Smith", occurs together often, the period is part of the name. Words that often start sentences, such as "However", also show a boundary.

The problem

The input is a text. Tokens are the runs of characters between white space; quotes and brackets at the ends of a token are ignored. The output marks, for each token, whether a sentence ends after it. A token with a final ? or ! always ends a sentence, and the last token ends the last sentence. For a token with a final period, the procedure must decide between a sentence period and an abbreviation period, and an abbreviation period can also end a sentence ("We sold pears etc. However, ..."). The type of a token is its word in lower case without the final marks, and every number is folded into one type NUMBER. A possible initial is a single letter with a period.

The algorithm

Let NN be the number of tokens, C(w)C(w) the number of tokens of type ww, C(w,∙)C(w, \bullet) the number of them with a final period, C(w,¬∙)C(w, \neg\bullet) the rest, and C(∙)C(\bullet) the number of tokens with a final period. The type stage uses the revised log likelihood ratio of the hypotheses P(∙∣w)=C(∙)/NP(\bullet \mid w) = C(\bullet)/N and P(∙∣w)=0.99P(\bullet \mid w) = 0.99, with k=C(w,∙)k = C(w, \bullet) and m=C(w,¬∙)m = C(w, \neg\bullet):

log⁡λ(w)=−2(kln⁡p+mln⁡(1−p)−kln⁡0.99−mln⁡0.01),p=C(∙)/N.\log\lambda(w) = -2\bigl(k \ln p + m \ln(1-p) - k \ln 0.99 - m \ln 0.01\bigr), \quad p = C(\bullet)/N.

The length len(w)\mathrm{len}(w) is the number of characters other than periods.

  1. PUNKT(t[1..N]) ▷ tokens with types, final marks and case
  2. 1count C(w), C(w, •), C(•) and N
  3. 2for each type w with a letter and C(w, •) > 0, other than NUMBER
  4. 3S(w) ← log λ(w) · e^(-len(w)) · (internal periods of w + 1) / len(w)^C(w, ¬•)
  5. 4w is an abbreviation if S(w) ≥ 0.3
  6. 5first pass: t[i] ends a sentence if it has a final ? or !, or a final period and a type that is not an abbreviation
  7. 6from the first pass, collect the case flags of each type, the frequent starters and the bigrams after a period
  8. 7for i ← 1 to N - 1 such that t[i] has a final period or is an ellipsis
  9. 8if t[i] is an ellipsis, or has an abbreviation type and is not a possible initial
  10. 9end[i] ← ORTHO(t[i+1]) = yes, or t[i+1] is capitalized and its type is a frequent starter
  11. 10else if t[i] is a possible initial or a number
  12. 11if COLLOC(t[i], t[i+1]) and t[i+1] is not a frequent starter, or ORTHO(t[i+1]) = no
  13. 12end[i] ← false
  14. 13else if t[i] is an initial, ORTHO(t[i+1]) = undecided, and t[i+1] is capitalized and its type is never seen in lower case
  15. 14end[i] ← false
  16. 15end[N] ← true; return end

Line L6 sets four flags for each type: seen with an upper case first letter at a sentence start, upper case inside a sentence, lower case at a start, and lower case inside. A token counts as a sentence start if the token before it is a first-pass boundary, and as inside a sentence if the token before it has no final mark. Tokens after an abbreviation, an ellipsis, an initial or a number are skipped, because their position is not yet known. The orthographic heuristic ORTHO (Figure 3 of the paper) says yes if the next token is capitalized, its type is seen in lower case, and it is never seen capitalized inside a sentence. It says no if the next token is in lower case and its type is seen capitalized or never seen in lower case at a sentence start, or if the next token is a punctuation mark. Otherwise it is undecided.

COLLOC and the frequent starters use Dunning's log likelihood ratio for a bigram, with p=C(w2)/Np = C(w_2)/N, p1=C(w1,w2)/C(w1)p_1 = C(w_1, w_2)/C(w_1) and p2=(C(w2)−C(w1,w2))/(N−C(w1))p_2 = (C(w_2) - C(w_1, w_2))/(N - C(w_1)), plus the one-sided condition C(w1,w2)/C(w1)>C(w2)/NC(w_1, w_2)/C(w_1) > C(w_2)/N. A pair is a collocation at log⁡λ≥7.88\log\lambda \ge 7.88, the 99.5% point of the chi-squared distribution with one degree of freedom. For the starters, w1w_1 is a sure sentence boundary: a first-pass boundary period on a token that is not an initial or a number. A type is a frequent starter at log⁡λ≥30\log\lambda \ge 30.

Example

The text is a block of 15 lines repeated 5 times, so that the counts are large enough: N = 445 tokens, of which C(•) = 120 have a final period, and 74 are sure sentence boundaries. One block is: "The dog met Dr. Brown at the park. We saw Dr. Brown and the cat. They sold apples, pears etc. and the rest. She came home late. However, the dog ran to the park. J. Smith saw the cat. The cat saw J. Smith at home. We bought pears etc. Then we went home. On 12. May the shop was closed. The park was quiet. We ate and then we slept. However, it rained. However, we stayed home. We sold pears etc. However, the cat slept. Mo. Brown left."

The type stage gives SS = 3.52 for dr (10 times with a period, never without), 1.94 for etc, 9.57 for j and 1.76 for mo, so these four are abbreviations. The type park has 10 periods but also 5 tokens without one, so log⁡λ=−16.9\log\lambda = -16.9 and it is not one. The type late has 5 periods and none without, but its length is 4 and S=0.238<0.3S = 0.238 < 0.3. The frequent starters are however (log⁡λ\log\lambda = 35.57) and we (33.17).

period next token line evidence first pass final
Dr. Brown L9 ORTHO undecided (brown is never seen in lower case), not a starter no no
etc. and L9 ORTHO no: and is in lower case and never seen in lower case at a sentence start no no
etc. Then L9 ORTHO yes: then is seen in lower case and never capitalized inside a sentence no yes
etc. However L9 ORTHO undecided, but However is capitalized and a frequent starter no yes
J. Smith L11 collocation j, smith with log⁡λ\log\lambda = 95.68 no no
12. May L11 collocation NUMBER, may with log⁡λ\log\lambda = 54.83, may is not a starter yes no
Mo. Brown L9 ORTHO undecided, not a starter no no
park. However none park is not an abbreviation, initial or number yes yes

The first pass makes 3 mistakes in each block (etc. Then, etc. However and 12. May), and the token stage corrects all 15 in the text. All 85 sentences are found. The same block repeated 8 times shows the weak point of the method: late, left and rest then reach S≥0.3S \ge 0.3 and become abbreviations, because they never occur without a period.

Correctness

Punkt is a heuristic classifier, so there is no guarantee that a decision is right. The proof in proofs/correctness.md shows that the procedure computes the decision rules of the paper, case by case, and that the statistics behave as the rules assume. It proves that log⁡λ(w)=2kln⁡(0.99/p)>0\log\lambda(w) = 2k\ln(0.99/p) > 0 for a type that never occurs without a period, which explains the pitfall above. It proves that Dunning's ratio is never negative and is 0 exactly when p1=p2p_1 = p_2, and that the one-sided condition holds exactly when p1>p2p_1 > p_2, so a frequent word that follows less often than expected is not taken as a collocation. The tests check the values of Table 1 and Table 2 of the paper and compare the procedure with a slow version that counts by scanning on 500 random texts.

Proof: Punkt applies the decision rules of Kiss and Strunk, and its statistics behave as statedfull

Punkt is a classifier, not an exact algorithm: its decisions can be wrong on real text, and its thresholds come from experiments. What can be proved is that the procedure computes the decision rules that Kiss and Strunk (2006) state, and that the statistics it uses have the properties that the rules rely on. Let the tokens be t1,…,tNt_1, \dots, t_N with types w(ti)w(t_i). Let C(w)C(w) be the number of tokens of type ww, C(w,∙)C(w, \bullet) the number of them with a final single period, C(w,¬∙)=C(w)−C(w,∙)C(w, \neg\bullet) = C(w) - C(w, \bullet), and C(∙)C(\bullet) the number of tokens with a final single period. Logarithms are natural. Write ℓ(k,n,x)=kln⁡x+(n−k)ln⁡(1−x)\ell(k, n, x) = k \ln x + (n - k) \ln (1 - x), with 0ln⁡0=00 \ln 0 = 0.

Lemma 1 (the type statistic). For a type ww with k=C(w,∙)k = C(w, \bullet) and m=C(w,¬∙)m = C(w, \neg\bullet), line L3 computes −2ln⁡(P0/PA)-2 \ln (P_0 / P_A), where P0P_0 and PAP_A are the binomial probabilities of kk periods in k+mk + m trials with p=C(∙)/Np = C(\bullet)/N and with 0.990.99. If m=0m = 0 and p<0.99p < 0.99, the value is 2kln⁡(0.99/p)>02k \ln(0.99/p) > 0.

Proof. Both binomial probabilities have the factor (k+mk)\binom{k+m}{k}, which cancels in the ratio, so −2ln⁡(P0/PA)=−2(ℓ(k,k+m,p)−ℓ(k,k+m,0.99))-2\ln(P_0/P_A) = -2(\ell(k, k+m, p) - \ell(k, k+m, 0.99)), which is the code. With m=0m = 0 the terms in 1−x1 - x vanish and the value is −2(kln⁡p−kln⁡0.99)=2kln⁡(0.99/p)-2(k \ln p - k \ln 0.99) = 2k \ln (0.99/p), which is positive when p<0.99p < 0.99. □\square

So a type that always has a period gets a positive score that grows linearly with kk. With the factors e−len(w)e^{-\mathrm{len}(w)} and (periods+1)(\text{periods} + 1) and no penalty, it is classified as an abbreviation as soon as k≥0.3 elen(w)/(2(periods+1)ln⁡(0.99/p))k \ge 0.3\, e^{\mathrm{len}(w)} / (2(\text{periods} + 1)\ln(0.99/p)). This is why a word that ends every sentence it occurs in, such as "late" in a small repetitive text, becomes an abbreviation once it is seen often enough.

Lemma 2 (the collocation statistic). Let 0<c1<N0 < c_1 < N, p=c2/Np = c_2/N, p1=c12/c1p_1 = c_{12}/c_1 and p2=(c2−c12)/(N−c1)p_2 = (c_2 - c_{12})/(N - c_1). Then Dunning's log⁡λ=2(ℓ(c12,c1,p1)+ℓ(c2−c12,N−c1,p2)−ℓ(c12,c1,p)−ℓ(c2−c12,N−c1,p))\log\lambda = 2(\ell(c_{12}, c_1, p_1) + \ell(c_2 - c_{12}, N - c_1, p_2) - \ell(c_{12}, c_1, p) - \ell(c_2 - c_{12}, N - c_1, p)) is at least 0, and it is 0 exactly when p1=p2p_1 = p_2.

Proof. For fixed kk and nn, the function x↦ℓ(k,n,x)x \mapsto \ell(k, n, x) on [0,1][0, 1] has its unique maximum at x=k/nx = k/n, because it is strictly concave where it is finite. So ℓ(c12,c1,p1)≥ℓ(c12,c1,p)\ell(c_{12}, c_1, p_1) \ge \ell(c_{12}, c_1, p) and ℓ(c2−c12,N−c1,p2)≥ℓ(c2−c12,N−c1,p)\ell(c_2 - c_{12}, N - c_1, p_2) \ge \ell(c_2 - c_{12}, N - c_1, p), with equality exactly when p1=pp_1 = p and p2=pp_2 = p. Since p=(c1p1+(N−c1)p2)/Np = (c_1 p_1 + (N - c_1) p_2)/N is a weighted mean of p1p_1 and p2p_2 with positive weights, p1=p=p2p_1 = p = p_2 holds exactly when p1=p2p_1 = p_2. □\square

Lemma 3 (the one-sided test). Under the hypotheses of Lemma 2, c12/c1>c2/Nc_{12}/c_1 > c_2/N holds exactly when p1>p2p_1 > p_2.

Proof. The left side is p1p_1 and the right side is pp, the weighted mean of p1p_1 and p2p_2 with positive weights. A number is larger than a strict mean of itself and another number exactly when it is larger than the other number. □\square

By Lemmas 2 and 3, the test in is_collocation accepts a pair only if w2w_2 follows w1w_1 more often than it follows other tokens, and the evidence is strong. Without the one-sided test, a very frequent w2w_2 that follows w1w_1 less often than expected would also get a large log⁡λ\log\lambda, which is the case of "ist" in Table 1 of the paper.

Lemma 4 (the statistics of line L6). After line L6, the case flags of a type ww record exactly the cases (first letter upper or lower case) and positions (sentence start or inside a sentence) of the tokens of type ww whose position the first pass decides. A token is at a sentence start if it is t1t_1 or if ti−1t_{i-1} is a first-pass boundary that is not an initial or a number, and inside a sentence if ti−1t_{i-1} has no final period, ellipsis, question mark or exclamation mark. All other tokens are skipped.

Proof. The loop in _statistics visits every token once. It skips tit_i exactly when ti−1t_{i-1} is an ellipsis, or has a final period and is not a first-pass boundary, or is an initial or a number with a final period. Otherwise it sets the start bit if ti−1t_{i-1} is a first-pass boundary and the inside bit if not; a token with a final ? or ! is always a first-pass boundary. The bits are combined with a bitwise or, so they record which cases occurred and not how often. □\square

Theorem. The procedure stops, and the flag ends[i] is true exactly in these cases.

  1. i=Ni = N, or tit_i ends in a question mark or an exclamation mark.
  2. tit_i has a final single period, is not an initial or a number, and its type is not an abbreviation.
  3. tit_i is an ellipsis, or has a final period and an abbreviation type and is not an initial, and the orthographic heuristic says yes for ti+1t_{i+1}, or ti+1t_{i+1} is capitalized and its type is a frequent sentence starter.
  4. tit_i is an initial or a number with a final period, it is a first-pass boundary, and none of the three rules of lines L11 and L13 applies: a collocation with ti+1t_{i+1} whose type is not a frequent starter, an orthographic "no" for ti+1t_{i+1}, or, for an initial, an undecided orthographic heuristic with a capitalized ti+1t_{i+1} whose type is never seen in lower case in a decided position.

Proof. Termination: every loop runs over the tokens, the types or the pairs a fixed number of times. For correctness, the flags start as the first pass of line L5, which is true exactly for a final ? or !, and for a final single period whose type is not an abbreviation. Line L15 sets the last flag. The loop of lines L7 to L14 changes ends[i] only for i<Ni < N and tit_i with a final period or an ellipsis, and the three branches are disjoint. A token of case 2 enters neither branch: it is not an ellipsis, its type is not an abbreviation, and it is not an initial or a number, so it keeps its first-pass value true. A token of case 3 enters the branch of line L8, which sets the flag to the stated condition, by Lemma 4 for the orthographic heuristic and by Lemmas 2 and 3 for the starters. An initial or a number enters the branch of line L10 (an initial is excluded from line L8 even if its type is an abbreviation). That branch only sets flags to false, so the flag is true exactly when the first pass made it true and no rule of lines L11 and L13 applies. Every other token has neither a final period nor an ellipsis, or has a ? or !, and keeps its first-pass value. ■\blacksquare

Remark. A number or an initial is never changed from "no boundary" to "boundary", as in the paper: a single letter that is not an abbreviation is expected to occur often without a period, so the type stage already treats it as an ordinary word. The theorem says nothing about the accuracy on real text. Kiss and Strunk report error rates between 0.35% and 2.12% on eleven corpora; that is a measurement.

Complexity

  • Time. Expected O(n)O(n) for a text of nn characters. Tokenization is one pass. The counts, the case flags, the bigram counts and the starters are hash table updates, one or two per token. Each decision of lines L7 to L14 looks up a constant number of counts.
  • Space. O(n)O(n) for the tokens and the tables of types and bigrams.

Properties

  • Unsupervised. All statistics come from the text itself; the paper applies Punkt to the text that it splits.
  • Few parameters. The values 0.99, 0.3, 7.88 and 30 are fixed. The paper found the scaling factors and thresholds by manual experiments on 10 MB of Wall Street Journal text and used them for all languages. They are rules of thumb, not derived values.
  • Language independent. The paper evaluates Punkt on newspaper text in eleven languages, with a mean accuracy of 99.38%, which is a measurement.
  • One-sided reclassification of initials and numbers. The token stage can only remove a boundary after an initial or a number, never add one.
  • Not online. All counts must be known before the first decision.

Variants and improvements

  • Separate training. NLTK splits Punkt into a trainer and a tokenizer: PunktTrainer learns the abbreviations, collocations and sentence starters from a corpus, and PunktSentenceTokenizer applies them to new text. NLTK ships pre-trained models, which avoids the small-text problem. Its formulas and default settings differ from the paper in details, so results differ.
  • Supervised methods. With labeled data, a classifier over features of the period context, such as the maximum entropy model of Reynar and Ratnaparkhi (1997), learns the decision directly. See sentence boundary detection.
  • Other marks. The paper treats ? and ! as sure boundaries. Text with colons, semicolons or line breaks as boundaries, or with no punctuation at all, needs other methods.

When to use it

Use Punkt for running text in a language that marks abbreviations with a period, when no labeled data and no abbreviation list are at hand, or when the text is from a new domain with its own abbreviations. Train it on a large amount of text from the same domain. For text that is all in upper case or all in lower case, the orthographic heuristic rarely decides, so expect more errors. For speech transcripts and text without punctuation, use a sequence model instead.

Pitfalls

  • A small or repetitive text. Line L4 classifies any short type that never occurs without a period as an abbreviation once it is frequent enough, so in a small text a word that always ends a sentence, such as "late", becomes an abbreviation. Train line L1 on a large text and apply the model to the target text.
  • The two-sided test. If line L11 uses log⁡λ≥7.88\log\lambda \ge 7.88 without the condition C(w1,w2)/C(w1)>C(w2)/NC(w_1, w_2)/C(w_1) > C(w_2)/N, a frequent word that follows w1w_1 less often than expected counts as a collocation. Table 1 of the paper shows this for the German "ist" after a sentence boundary, with log⁡λ\log\lambda = 169.8. Keep the one-sided condition.
  • Numbers before frequent words. Line L11 can find a collocation of NUMBER with a common word such as "the" if many sentences end in a number and the next starts with "The". The period after the number is then never a boundary. A frequent starter blocks the collocation, which is why line L11 checks it.
  • Initials in the abbreviation branch. If line L8 also takes possible initials, an initial is judged only by ORTHO and the starters, and the collocation rule and the proper name rule of lines L11 and L13 are lost. Send single letters to line L10, as the paper does.
  • Counting unknown positions. If line L6 counts the token after an abbreviation as inside a sentence, as the first pass says, then "etc. Then" gives the type then an upper case inside bit, and ORTHO can no longer say yes for it. Skip tokens whose position is not decided.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

punkt_sentence_tokenizer.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/punkt-sentence-tokenizer/. The authors are listed in prov/BAJBZ1.jsonl.

"""Punkt sentence boundary detection, after Kiss and Strunk (2006).

The method is unsupervised: it learns from the text that it splits. A type-based
stage finds abbreviation types by a scaled likelihood ratio. A token-based stage
then looks at the word after each period and decides with three heuristics: the
orthographic heuristic, the collocation heuristic and the frequent sentence
starter heuristic.

Tokens are the runs of non-space characters. Quotes and brackets at the two ends
of a token are ignored, so 'end.)' is a token with a final period. The type of a
token is its word in lower case, without the final marks; a word of digits is
folded into the type NUMBER, as in the paper.

The thresholds 0.3, 7.88 and 30 and the value 0.99 are the ones of the paper,
which found them by manual experiments on Wall Street Journal text.
"""

import math
import re
from collections import Counter
from dataclasses import dataclass
from typing import Dict, List, Optional, Set, Tuple

NUMBER = "##number##"
OPENERS = "\"'([{"
CLOSERS = "\"')]}"
NUMBER_RE = re.compile(r"\d+(?:[.,]\d+)*")
P_ABBREV = 0.99
ABBREV_THRESHOLD = 0.3
COLLOCATION_THRESHOLD = 7.88
STARTER_THRESHOLD = 30.0

UC_START, LC_START, UC_MID, LC_MID = 1, 2, 4, 8


@dataclass(frozen=True)
class Token:
    start: int  # the token covers text[start:end]
    end: int
    kind: str  # "." final period, "..." ellipsis, "?" for ? or !, "" no final mark
    word: str  # the word in its original case, without the final marks
    type: str  # the word in lower case; digits are folded into NUMBER


def tokenize(text: str) -> List[Token]:
    """Split a text at white space and classify the final mark of each token."""
    out = []
    for m in re.finditer(r"\S+", text):
        q = m.group().lstrip(OPENERS).rstrip(CLOSERS)
        if q.endswith("..."):
            kind = "..."
        elif q.endswith("."):
            kind = "."
        elif q[-1:] in ("?", "!"):
            kind = "?"
        else:
            kind = ""
        word = q.rstrip(".?!,;:") or q or m.group()
        typ = word.lower()
        if NUMBER_RE.fullmatch(typ):
            typ = NUMBER
        out.append(Token(m.start(), m.end(), kind, word, typ))
    return out


def _xlogy(k: float, x: float) -> float:
    """k * ln x, with 0 * ln 0 = 0."""
    if k == 0:
        return 0.0
    if x <= 0.0:
        return -math.inf
    return k * math.log(x)


def _binom_ll(k: int, n: int, x: float) -> float:
    """ln of x^k (1-x)^(n-k); the binomial coefficient cancels in each ratio."""
    return _xlogy(k, x) + _xlogy(n - k, 1.0 - x)


def abbreviation_log_lambda(c_with: int, c_without: int, c_period: int, n: int) -> float:
    """Revised log lambda of the type stage: P(. | w) = C(.)/N against P(. | w) = 0.99."""
    k, m = c_with, c_with + c_without
    p = c_period / n
    return -2.0 * (_binom_ll(k, m, p) - _binom_ll(k, m, P_ABBREV))


def abbreviation_score(w: str, c_with: int, c_without: int, c_period: int, n: int) -> float:
    """log lambda times F_length, F_periods and F_penalty, as in Kiss and Strunk."""
    periods = w.count(".")
    length = len(w) - periods
    ll = abbreviation_log_lambda(c_with, c_without, c_period, n)
    return ll * math.exp(-length) * (periods + 1) / length ** c_without


def dunning_log_lambda(c1: int, c2: int, c12: int, n: int) -> float:
    """Dunning's log likelihood ratio for the bigram w1 w2, from C(w1), C(w2), C(w1, w2), N."""
    p = c2 / n
    p1 = c12 / c1
    p2 = (c2 - c12) / (n - c1) if n > c1 else 0.0
    return -2.0 * (_binom_ll(c12, c1, p) + _binom_ll(c2 - c12, n - c1, p)
                   - _binom_ll(c12, c1, p1) - _binom_ll(c2 - c12, n - c1, p2))


def is_collocation(c1: int, c2: int, c12: int, n: int, threshold: float) -> bool:
    """log lambda at least the threshold, and the one-sided test C(w1, w2)/C(w1) > C(w2)/N."""
    if c1 == 0 or c12 == 0:
        return False
    return dunning_log_lambda(c1, c2, c12, n) >= threshold and c12 * n > c2 * c1


def is_initial(t: Token) -> bool:
    return t.kind == "." and len(t.type) == 1 and t.type.isalpha()


def is_number(t: Token) -> bool:
    return t.kind == "." and t.type == NUMBER


@dataclass
class Model:
    count: Counter
    abbrevs: Set[str]
    ortho: Dict[str, int]
    starters: Set[str]
    pairs: Counter
    n: int


def _ortho(u: Token, model: Model) -> Optional[bool]:
    """True: boundary before u, False: no boundary, None: undecided (Figure 3 of the paper)."""
    if all(ch in ";:,.!?" for ch in u.word):
        return False
    flags = model.ortho.get(u.type, 0)
    first = u.word[:1]
    if first.isupper() and flags & (LC_START | LC_MID) and not flags & UC_MID:
        return True
    if first.islower() and (flags & (UC_START | UC_MID) or not flags & LC_START):
        return False
    return None


def _colloc(t: Token, u: Token, model: Model) -> bool:
    c = model.count
    return is_collocation(c[t.type], c[u.type], model.pairs[(t.type, u.type)], model.n,
                          COLLOCATION_THRESHOLD)


def _statistics(toks: List[Token], first: List[bool], count: Counter, abbrevs: Set[str]) -> Model:
    """Case statistics, frequent sentence starters and bigram counts after a period."""
    n = len(toks)
    ortho: Dict[str, int] = {}
    for i, t in enumerate(toks):
        if i == 0:
            start = True
        else:
            prev = toks[i - 1]
            if prev.kind == "..." or (prev.kind == "." and (not first[i - 1] or is_initial(prev) or is_number(prev))):
                continue  # position unknown: after an abbreviation, an ellipsis, an initial or a number
            start = first[i - 1]
        c = t.word[:1]
        if c.isupper():
            ortho[t.type] = ortho.get(t.type, 0) | (UC_START if start else UC_MID)
        elif c.islower():
            ortho[t.type] = ortho.get(t.type, 0) | (LC_START if start else LC_MID)
    sure = [i for i in range(n - 1)
            if toks[i].kind == "." and first[i] and not is_initial(toks[i]) and not is_number(toks[i])]
    after_sure = Counter(toks[i + 1].type for i in sure)
    starters = {w for w, k in after_sure.items()
                if is_collocation(len(sure), count[w], k, n, STARTER_THRESHOLD)}
    pairs = Counter((toks[i].type, toks[i + 1].type) for i in range(n - 1) if toks[i].kind == ".")
    return Model(count, abbrevs, ortho, starters, pairs, n)


def punkt(text: str) -> Tuple[List[Token], List[bool], Model]:
    """Return the tokens, a flag per token that is True if a sentence ends after it, and the model.

    Cost: O(len(text)) expected time and space, with hash tables for the counts.
    """
    toks = tokenize(text)
    n = len(toks)
    count = Counter(t.type for t in toks)  # @line L1
    with_period = Counter(t.type for t in toks if t.kind == ".")
    c_period = sum(with_period.values())
    abbrevs: Set[str] = set()
    for w, k in with_period.items():  # @line L2
        if w == NUMBER or not any(ch.isalpha() for ch in w):
            continue
        s = abbreviation_score(w, k, count[w] - k, c_period, n)  # @line L3
        if s >= ABBREV_THRESHOLD:  # @line L4
            abbrevs.add(w)
    first = [t.kind == "?" or (t.kind == "." and t.type not in abbrevs) for t in toks]  # @line L5
    model = _statistics(toks, first, count, abbrevs)  # @line L6
    ends = list(first)
    for i in range(n - 1):  # @line L7
        t, u = toks[i], toks[i + 1]
        if t.kind not in (".", "..."):
            continue
        if t.kind == "..." or (t.type in abbrevs and not is_initial(t)):  # @line L8
            ends[i] = _ortho(u, model) is True or (u.word[:1].isupper() and u.type in model.starters)  # @line L9
        elif is_initial(t) or is_number(t):  # @line L10
            o = _ortho(u, model)
            if (_colloc(t, u, model) and u.type not in model.starters) or o is False:  # @line L11
                ends[i] = False  # @line L12
            elif is_initial(t) and o is None and u.word[:1].isupper() \
                    and model.ortho.get(u.type, 0) & (LC_START | LC_MID) == 0:  # @line L13
                ends[i] = False  # @line L14
    if n:
        ends[-1] = True  # @line L15
    return toks, ends, model


def split_sentences(text: str) -> List[str]:
    """Split a text into sentences with Punkt trained on the same text."""
    toks, ends, _ = punkt(text)
    out, begin = [], None
    for t, e in zip(toks, ends):
        if begin is None:
            begin = t.start
        if e:
            out.append(text[begin:t.end])
            begin = None
    return out
test_punkt_sentence_tokenizer.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/punkt-sentence-tokenizer/. The authors are listed in prov/BAJBZ1.jsonl.

import math
import random

from punkt_sentence_tokenizer import (
    NUMBER, abbreviation_log_lambda, abbreviation_score, dunning_log_lambda, punkt, split_sentences,
    tokenize,
)

# A block of lines; three of them hold two sentences. The page example repeats it 5 times.
BLOCK = [
    "The dog met Dr. Brown at the park.", "We saw Dr. Brown and the cat.",
    "They sold apples, pears etc. and the rest.", "She came home late.",
    "However, the dog ran to the park.", "J. Smith saw the cat.", "The cat saw J. Smith at home.",
    "We bought pears etc. Then we went home.", "On 12. May the shop was closed.", "The park was quiet.",
    "We ate and then we slept.", "However, it rained.", "However, we stayed home.",
    "We sold pears etc. However, the cat slept.", "Mo. Brown left.",
]
TRUE_SENTENCES = []
for line in BLOCK:
    if line == "We bought pears etc. Then we went home.":
        TRUE_SENTENCES += ["We bought pears etc.", "Then we went home."]
    elif line == "We sold pears etc. However, the cat slept.":
        TRUE_SENTENCES += ["We sold pears etc.", "However, the cat slept."]
    else:
        TRUE_SENTENCES.append(line)


def test_table2_of_the_paper():
    # Kiss and Strunk (2006), Table 2: N = 351,529 WSJ tokens. C(.) is not given in the paper;
    # 20,994 periods (p = 0.0597) reproduce the printed values.
    n, c_period = 351529, 20994
    rows = [  # type, C(w, .), C(w, not .), revised log lambda, scaled log lambda
        ("n.h", 5, 0, 28.08, 7.60), ("u.s.a", 5, 0, 28.08, 4.19), ("alex", 8, 2, 26.75, 0.03),
        ("ounces", 4, 0, 22.46, 0.06), ("a.g", 4, 0, 22.46, 6.08), ("ga", 4, 0, 22.46, 3.04),
        ("vt", 4, 0, 22.46, 3.04), ("ore", 5, 1, 18.99, 0.32), ("mo", 8, 3, 17.67, 0.30),
        ("m.j", 3, 0, 16.85, 4.56), ("depositor", 3, 0, 16.85, 0.00), ("reps", 3, 0, 16.85, 0.31),
        ("u.n", 3, 0, 16.85, 4.56),
    ]
    for w, k, m, ll, scaled in rows:
        assert round(abbreviation_log_lambda(k, m, c_period, n), 2) == ll
        assert round(abbreviation_score(w, k, m, c_period, n), 2) == scaled
    # The table prints 0.26 for 1990s (5, 1); the formula of the paper gives 18.99 e^-5 / 5 = 0.03.
    assert round(abbreviation_score("1990s", 5, 1, c_period, n), 2) == 0.03
    # mo is printed as 0.30, but its unrounded score is just below the threshold 0.3.
    assert 0.298 < abbreviation_score("mo", 8, 3, c_period, n) < 0.3


def test_table1_of_the_paper():
    # Frequent sentence starters in German: C(<S>) = 35,775, N = 847,206.
    n, cs = 847206, 35775
    rows = [("ist", 9758, 182, 169.8390), ("zu", 7643, 71, 298.8915),
            ("dennoch", 231, 80, 221.4709), ("erstens", 38, 21, 82.1377)]
    for w, c2, c12, ll in rows:
        assert abs(dunning_log_lambda(cs, c2, c12, n) - ll) < 0.002
    # The one-sided test keeps dennoch and erstens and drops ist and zu.
    assert [c12 * n > c2 * cs for _, c2, c12, _ in rows] == [False, False, True, True]


def test_tokenize():
    toks = tokenize('He said "end.)" at 12. U.S. wait... Why? Dr. x')
    assert [(t.kind, t.word, t.type) for t in toks] == [
        ("", "He", "he"), ("", "said", "said"), (".", "end", "end"), ("", "at", "at"),
        (".", "12", NUMBER), (".", "U.S", "u.s"), ("...", "wait", "wait"), ("?", "Why", "why"),
        (".", "Dr", "dr"), ("", "x", "x"),
    ]
    assert toks[2].start == 8 and toks[2].end == 15


def test_page_example():
    text = " ".join(BLOCK * 5)
    toks, ends, model = punkt(text)
    assert len(toks) == 445 and sum(t.kind == "." for t in toks) == 120
    assert model.abbrevs == {"dr", "etc", "j", "mo"}
    assert model.starters == {"however", "we"}
    assert split_sentences(text) == TRUE_SENTENCES * 5
    # Without the token stage, three periods in each block are wrong.
    first = [t.kind == "?" or (t.kind == "." and t.type not in model.abbrevs) for t in toks]
    first[-1] = True
    assert sum(a != b for a, b in zip(first, ends)) == 3 * 5


def test_small_text_pitfall():
    # Words that always end a sentence look like abbreviations when the text is small and repetitive.
    _, _, model = punkt(" ".join(BLOCK * 8))
    assert {"late", "left", "rest"} <= model.abbrevs


def test_edge_cases():
    assert punkt("")[1] == [] and split_sentences("") == []
    assert split_sentences("no period here") == ["no period here"]
    assert split_sentences("Why? Because.") == ["Why?", "Because."]
    assert split_sentences("  Hello.  ") == ["Hello."]


# ---------------------------------------------------------------------------
# A slow oracle that counts by scanning the token list for every question.

def _logpmf(k, n, x):
    if (k > 0 and x <= 0.0) or (n - k > 0 and x >= 1.0):
        return -math.inf
    out = math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
    if k > 0:
        out += k * math.log(x)
    if n - k > 0:
        out += (n - k) * math.log(1.0 - x)
    return out


def _dunning(c1, c2, c12, n):
    p, p1 = c2 / n, c12 / c1
    p2 = (c2 - c12) / (n - c1) if n > c1 else 0.0
    return 2.0 * (_logpmf(c12, c1, p1) + _logpmf(c2 - c12, n - c1, p2)
                  - _logpmf(c12, c1, p) - _logpmf(c2 - c12, n - c1, p))


def oracle_ends(text):
    toks = tokenize(text)
    n = len(toks)
    if n == 0:
        return []
    memo = {}

    def count(w):
        if ("c", w) not in memo:
            memo[("c", w)] = sum(t.type == w for t in toks)
        return memo[("c", w)]

    c_dot = sum(t.kind == "." for t in toks)

    def abbrev(w):
        key = ("a", w)
        if key not in memo:
            k = sum(t.type == w and t.kind == "." for t in toks)
            ok = False
            if k > 0 and w != NUMBER and any(ch.isalpha() for ch in w):
                m = count(w) - k
                ll = -2.0 * (_logpmf(k, k + m, c_dot / n) - _logpmf(k, k + m, 0.99))
                length = len(w) - w.count(".")
                ok = ll * math.exp(-length) * (w.count(".") + 1) / length ** m >= 0.3
            memo[key] = ok
        return memo[key]

    def initial(t):
        return t.kind == "." and len(t.type) == 1 and t.type.isalpha()

    def number(t):
        return t.kind == "." and t.type == NUMBER

    first = [t.kind == "?" or (t.kind == "." and not abbrev(t.type)) for t in toks]

    def position(i):
        if i == 0:
            return "start"
        p = toks[i - 1]
        if p.kind == "..." or (p.kind == "." and (not first[i - 1] or initial(p) or number(p))):
            return None
        return "start" if first[i - 1] else "mid"

    def seen(w, upper, where):
        for i, t in enumerate(toks):
            if t.type != w:
                continue
            c = t.word[:1]
            if (c.isupper() if upper else c.islower()) and position(i) in where:
                return True
        return False

    def ortho(u):
        if all(ch in ";:,.!?" for ch in u.word):
            return False
        w, c = u.type, u.word[:1]
        if c.isupper() and seen(w, False, ("start", "mid")) and not seen(w, True, ("mid",)):
            return True
        if c.islower() and (seen(w, True, ("start", "mid")) or not seen(w, False, ("start",))):
            return False
        return None

    sure = [i for i in range(n - 1)
            if toks[i].kind == "." and first[i] and not initial(toks[i]) and not number(toks[i])]

    def starter(w):
        c12 = sum(toks[i + 1].type == w for i in sure)
        return c12 > 0 and _dunning(len(sure), count(w), c12, n) >= 30 and c12 * n > count(w) * len(sure)

    def colloc(t, u):
        c12 = sum(toks[j].kind == "." and toks[j].type == t.type and toks[j + 1].type == u.type
                  for j in range(n - 1))
        c1 = count(t.type)
        return c12 > 0 and _dunning(c1, count(u.type), c12, n) >= 7.88 and c12 * n > count(u.type) * c1

    ends = list(first)
    for i in range(n - 1):
        t, u = toks[i], toks[i + 1]
        if t.kind == "..." or (t.kind == "." and abbrev(t.type) and not initial(t)):
            ends[i] = ortho(u) is True or (u.word[:1].isupper() and starter(u.type))
        elif initial(t) or number(t):
            o = ortho(u)
            if (colloc(t, u) and not starter(u.type)) or o is False:
                ends[i] = False
            elif initial(t) and o is None and u.word[:1].isupper() and not seen(u.type, False, ("start", "mid")):
                ends[i] = False
    ends[-1] = True
    return ends


WORDS = ["The", "the", "Dr.", "dr.", "etc.", "Then", "then", "However,", "J.", "Smith", "12.", "7",
         "May", "may", "wait...", "Why?", "No!", "cat", "cat.", "dog.", "Brown", "park.", "U.S.", "a", "A",
         "and", "we", "We", ",", '"Hi."', "(end.)", "--", "x."]


def test_random_against_oracle():
    rng = random.Random(2006)
    for case in range(500):
        if case % 2 == 0:
            text = " ".join(rng.choice(WORDS) for _ in range(rng.randint(0, 60)))
        else:
            text = " ".join(rng.choice(BLOCK) for _ in range(rng.randint(1, 45)))
        toks, ends, model = punkt(text)
        assert ends == oracle_ends(text)
        if toks:
            assert ends[-1]
        for t, e in zip(toks[:-1], ends[:-1]):
            if t.kind == "?":
                assert e
            elif t.kind == "":
                assert not e
            elif t.kind == "." and t.type not in model.abbrevs and t.type != NUMBER and len(t.type) != 1:
                assert e  # an ordinary word with a period always ends a sentence
        assert "".join(split_sentences(text)).replace(" ", "") == text.replace(" ", "")

History

Tibor Kiss and Jan Strunk first described abbreviation detection as collocation detection with a log likelihood ratio in 2002. Their 2006 paper in Computational Linguistics added the scaling factors, the token-based stage with the orthographic, collocation and frequent starter heuristics, and the special handling of initials and ordinal numbers. It reported error rates from 0.35% to 2.12% on newspaper corpora in eleven languages, with a mean of 1.26%, against a mean of 1.77% for the supervised MxTerminator, which the authors trained on the same corpora. NLTK later made Punkt its standard sentence splitter.

References

  1. Tibor Kiss and Jan Strunk, Unsupervised multilingual sentence boundary detection, Computational Linguistics 32(4), 2006, pages 485 to 525; Section 2 (likelihood ratios), Section 3 (type-based stage, Table 2), Section 4 (token-based stage, Figure 3), Section 5 (development), Section 6 (evaluation)
  2. Ted Dunning, Accurate methods for the statistics of surprise and coincidence, Computational Linguistics 19(1), 1993, pages 61 to 74 (the log likelihood ratio for bigrams)
  3. NLTK documentation, module nltk.tokenize.punkt, the classes PunktTrainer and PunktSentenceTokenizer

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.expected
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example