How it works

N-gram Text Generator

← Back to the demos

The generator never learns grammar or meaning. It counts which words follow which word sequences in your text, then writes new text by repeatedly picking a plausible next word. The sequence length n is how many previous words it looks at.

Phase 1: build the model

flowchart LR
  A["Split the text into words"] --> B["Slide a window of n words across the text"]
  B --> C["Window = key, the word right after it = follower"]
  C --> D["Append the follower to that key's list"]

With n = 2, the text the cat sat on the cat ran produces:

Key (2 words)Followers seen
the catsat, ran
cat saton
sat onthe
on thecat

Phase 2: generate text

flowchart TD
  A["Pick a starting key, preferring one that begins with a capital letter"] --> B["Look up the followers of the current key"]
  B --> C{"Any followers?"}
  C -- yes --> D["Pick one at random"]
  D --> E["Append it to the output"]
  E --> F["New key = the last n words of the output"]
  C -- no --> G["Dead end: jump to a random key"]
  G --> B
  F --> H{"Reached the requested length?"}
  H -- no --> B
  H -- yes --> I["Show the text"]

Why it works

← Back to the demos