Project 31: Markov Meme Writer 🤡¶

Difficulty: 🟡 Intermediate

Run cells top to bottom. Each step builds on the previous one and saves real files under outputs/markov_meme_writer/.

← Back to index

Description¶

Train a tiny Markov chain on sample sentences and generate absurd meme captions.

Libraries & Modules¶

  • random, collections.defaultdict

Python Concepts You'll Practice¶

Tokenization, graph-like dicts, generative text

🎛️ Parameter Variations¶

  • ORDER — Markov memory (1–2)
  • LENGTH — words to generate
  • Paste your own training corpus
In [1]:
# Install dependencies for this project (safe to re-run)
import sys
!{sys.executable} -m pip install pillow numpy matplotlib wordcloud qrcode[pil] python-barcode fpdf2 jinja2 folium plotly pandas scipy ipywidgets -q
Skipping pip install (already installed)
In [2]:
# Interactive Jupyter setup — run this cell first
%matplotlib inline

from pathlib import Path
from IPython.display import display, Image as IPImage, HTML, Markdown, Audio, IFrame

OUTPUT_DIR = Path("outputs") / "markov_meme_writer"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
print(f"✅ Outputs folder: {OUTPUT_DIR.resolve()}")
✅ Outputs folder: C:\Users\Hansel Yan\Projects\CodeItAll\outputs\markov_meme_writer

Step 1 — Train on a silly corpus¶

In [3]:
import random
from collections import defaultdict

# 🎛️ TWEAK THESE
ORDER = 1
LENGTH = 18
SEED = 42
CORPUS = '''
code is poetry and bugs are plot twists
ship it friday and debug it monday
python snakes through data like neon noodles
coffee fuels commits more than luck
ai assistants amplify curious humans
pixels dance when loops feel brave
'''

random.seed(SEED)
words = CORPUS.lower().replace("\n", " ").split()
model = defaultdict(list)
for i in range(len(words) - ORDER):
    key = tuple(words[i:i + ORDER])
    model[key].append(words[i + ORDER])
print(f"Model keys: {len(model)}")
Model keys: 36

Step 2 — Generate captions¶

In [4]:
captions = []
for _ in range(5):
    state = random.choice(list(model.keys()))
    out = list(state)
    for _ in range(LENGTH - ORDER):
        choices = model.get(state)
        if not choices:
            break
        nxt = random.choice(choices)
        out.append(nxt)
        state = tuple(out[-ORDER:])
    captions.append(" ".join(out))

text = "\n".join(f"- {c}" for c in captions)
print(text)
(OUTPUT_DIR / "markov_memes.txt").write_text(text, encoding="utf-8")
print("Saved markov_memes.txt")
- twists ship it friday and bugs are plot twists ship it friday and bugs are plot twists ship
- amplify curious humans pixels dance when loops feel brave
- fuels commits more than luck ai assistants amplify curious humans pixels dance when loops feel brave
- bugs are plot twists ship it friday and debug it monday python snakes through data like neon noodles
- loops feel brave
Saved markov_memes.txt

✅ Project complete¶

Check your output folder: outputs/markov_meme_writer/

Next: Project 32: Budget Pie Party · Index