DEV Community

Emma Jansen
Emma Jansen

Posted on

A word budget for every section: a small script that keeps drafts in proportion

Most of my drafts don't fail because of bad sentences. They fail because of proportions. The introduction takes 300 words to get going, the important section gets 80, and the conclusion repeats the introduction. Nobody decided that. It just happened while I was typing.

What helped me was something I borrowed from software: a budget. Before I write, I decide how many words each section is allowed to have. Afterwards, a short script tells me where the draft ignored the plan.

The budget file

A plain text file, one line per section, with a minimum and a maximum:

# section: min-max words
intro: 40-80
why it matters: 60-120
what we tried: 100-160
next steps: 30-60
Enter fullscreen mode Exit fullscreen mode

Writing this takes two minutes, and it forces the useful questions early. Which part matters most? What can the reader do without? If "next steps" gets 30 words, I already know it shouldn't turn into a second article.

The script

It reads the draft, splits it at every ## heading, counts words per section (ignoring fenced code blocks) and compares them with the budget:

#!/usr/bin/env python3
import re
import sys
from pathlib import Path

FENCE = "`" * 3


def load_budget(path):
    budget = {}
    for line in Path(path).read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        name, _, limits = line.rpartition(":")
        low, _, high = limits.partition("-")
        budget[name.strip().lower()] = (int(low), int(high))
    return budget


def split_sections(text):
    sections = [("intro", [])]
    in_code = False
    for line in text.splitlines():
        if line.strip().startswith(FENCE):
            in_code = not in_code
            continue
        if in_code:
            continue
        if line.startswith("## "):
            sections.append((line[3:].strip().lower(), []))
        elif not line.startswith("# "):
            sections[-1][1].append(line)
    return [(name, " ".join(lines)) for name, lines in sections]


def count_words(text):
    return len(re.findall(r"[\w'’-]+", text))


def main(draft, budget_file):
    budget = load_budget(budget_file)
    problems = 0
    for name, body in split_sections(Path(draft).read_text(encoding="utf-8")):
        words = count_words(body)
        if name not in budget:
            print(f"{name:<24}{words:>5}   (no budget)")
            continue
        low, high = budget[name]
        status = "ok"
        if words < low:
            status = f"short by {low - words}"
        elif words > high:
            status = f"over by {words - high}"
        problems += status != "ok"
        print(f"{name:<24}{words:>5}   {low}-{high}   {status}")
    return 1 if problems else 0


if __name__ == "__main__":
    if len(sys.argv) != 3:
        sys.exit("usage: budget.py draft.md budget.txt")
    sys.exit(main(sys.argv[1], sys.argv[2]))
Enter fullscreen mode Exit fullscreen mode

Run it like this:

python3 budget.py draft.md budget.txt
Enter fullscreen mode Exit fullscreen mode

What the output looks like

intro                      55   40-80   ok
why it matters             90   60-120   ok
what we tried             190   100-160   over by 30
next steps                 20   30-60   short by 10
extras                     30   (no budget)
Enter fullscreen mode Exit fullscreen mode

Three things I like about this output. The "over by" and "short by" numbers tell me exactly how much to cut or add. A section with no budget shows up as "(no budget)", so a heading I forgot to plan can't hide. And the script exits with code 1 when something is off, so you can wire it into a pre-commit hook or a CI step if you keep drafts in a repository.

A few notes on how it works

  • Text before the first ## heading counts as the intro section, so the budget file needs a line with that name.
  • Headings are matched in lower case, so ## Next Steps and next steps are the same section.
  • Code blocks are skipped, because you usually don't want sample code counted as prose.
  • The word counter is deliberately simple. It treats anything made of letters, digits, apostrophes and hyphens as a word, which is close enough for budgeting.

Where the budget goes wrong

A budget is a starting point. Sometimes the draft is right and the plan was wrong, for example when a section turns out to need more room because it carries the actual argument. That is a good reason to change the number. The point is that you change it on purpose, rather than discovering the imbalance after publishing.

The other trap is treating the limits as a target. If a section lands at exactly the maximum, it doesn't mean the text is good. It only means it is the right size.

Make it a habit

I keep a copy of the script next to my drafts and a budget file per article. The whole routine takes about five minutes: write the budget before the draft, run the script after the first complete version, fix the biggest imbalance, run it again.

It won't make a sentence better. But it keeps the shape of the piece honest, and that is the part I used to get wrong without noticing.

Top comments (0)