Extractive text summarization

File: summarizer.lisp

A classic method from before neural networks: score each sentence by the average frequency of its significant words, keep the top few, and print them in their original order.

math

where Code Test counts occurrences of word Code Test across the whole document. Words on a short stop-word list get a frequency of zero, but they still count toward the sentence length Code Test, so filler words lower a sentence’s score.

The code

 1 ;; sbcl --script summarizer.lisp (extractive text summarization)
 2 
 3 (defparameter *stop-words*
 4   '("the" "a" "an" "in" "on" "at" "to" "for" "of" "and" "or" "is"
 5     "are" "was" "were" "it" "that" "this" "with" "as" "by" "from"
 6     "be" "has" "have" "its"))
 7 
 8 (defun words (text)
 9   (loop with len = (length text) and acc = nil and res = nil
10         for i from 0 below len
11         for ch = (char text i)
12         do (if (alphanumericp ch)
13                (push (char-downcase ch) acc)
14                (when acc
15                  (push (coerce (nreverse acc) 'string) res)
16                  (setf acc nil)))
17         finally (when acc (push (coerce (nreverse acc) 'string) res))
18                 (return (nreverse res))))
19 
20 (defun split-sentences (text)
21   (loop with len = (length text) and start = 0 and res = nil
22         for i from 0 below len
23         for ch = (char text i)
24         when (member ch '(#\. #\! #\?))
25           do (let ((s (string-trim '(#\Space #\Tab #\Newline #\Return)
26                                    (subseq text start (1+ i)))))
27                (when (> (length s) 0) (push s res))
28                (setf start (1+ i)))
29         finally (let ((s (string-trim
30                           '(#\Space #\Tab #\Newline #\Return)
31                           (subseq text start len))))
32                   (when (> (length s) 0) (push s res)))
33                 (return (nreverse res))))
34 
35 (defun summarize (text &optional (n 2))
36   (let* ((sentences (split-sentences text))
37          (freqs (make-hash-table :test 'equal)))
38     (dolist (s sentences)
39       (dolist (w (words s))
40         (unless (member w *stop-words* :test #'string=)
41           (incf (gethash w freqs 0)))))
42     (let ((scored
43             (loop for s in sentences for idx from 0
44                   for ws = (words s)
45                   for score = (if (null ws) 0.0
46                                   (/ (loop for w in ws
47                                            sum (gethash w freqs 0))
48                                      (float (length ws))))
49                   collect (list score idx s))))
50       (mapcar #'third
51               (sort (subseq (stable-sort scored #'> :key #'first)
52                             0 (min n (length scored)))
53                     #'< :key #'second)))))
54 
55 ;; Demo: Multi-sentence paragraph extraction
56 (let* ((text
57         (concatenate
58          'string
59          "Common Lisp is an expressive, multi-paradigm programming "
60          "language with a rich history in artificial intelligence. "
61          "It features dynamic typing, an advanced object system, "
62          "and syntactic macros that allow programmers to create "
63          "domain-specific languages. "
64          "Extractive summarization algorithms score sentences based "
65          "on significant word frequencies across a document. "
66          "In this example, we calculate term frequencies and rank "
67          "sentences to produce a concise summary. "
68          "Common Lisp continues to empower developers to build "
69          "complex symbolic and numerical systems with high "
70          "productivity."))
71        (summary (summarize text 2)))
72   (format t "Original text: ~a sentences.~%~%"
73           (length (split-sentences text)))
74   (format t "Extractive 2-Sentence Summary:~%")
75   (dolist (s summary)
76     (format t "  • ~a~%" s)))

How it works

  • words and split-sentences use the same hand-written scanner pattern as the BM25 chapter: loop over characters, collect them, and emit at boundaries. Sentences end at ., !, or ?. (words copies BM25’s tokenize; six duplicated lines keep every file in this book self-contained.)
  • An equal hash table counts word frequencies and skips *stop-words*, so common function words do not dominate the scores.
  • A sentence’s score is the average of its word frequencies; dividing by sentence length stops long sentences from winning just by having more words.
  • The last expression needs care: sort by score in descending order, take the top n with subseq, then sort again by sentence index in ascending order. The second sort restores document order so the summary reads naturally. The first sort is a stable-sort: plain sort may reorder equal elements arbitrarily, so with ties at the cutoff the chosen sentences could differ between Lisp implementations. stable-sort keeps tied sentences in document order, so earlier sentences win ties.
  • summarize never changes its input; the (score idx s) lists carry each sentence’s index through both sorts.

Running it

1 $ sbcl --script summarizer.lisp

Actual output:

1 Original text: 5 sentences.
2 
3 Extractive 2-Sentence Summary:
4   • Extractive summarization algorithms score sentences based on significant word frequencies across a document.
5   • Common Lisp continues to empower developers to build complex symbolic and numerical systems with high productivity.

Using it

Pass it the output of the web-scraping chapter: (summarize (page-text url) 3) summarizes the web page at url without any AI service. It also works as a first pass before an LLM: pick the top sentences locally, then ask Gemini or Ollama to rewrite just those. Adjust *stop-words* for your domain, and treat the sentence splitter as a heuristic (abbreviations like “Dr.” fool it).