Exercise 1 solution: judging text settings ========================================= Save this as check_settings.py and run it with: py check_settings.py (It needs fontTools: py -m pip install fonttools) """Check text settings: wrap a paragraph and judge the line length and spacing.""" from pathlib import Path from fontTools.ttLib import TTFont FONT_DIR = Path("C:/Windows/Fonts") FONTS = {"Georgia": "georgia.ttf", "Arial": "arial.ttf"} TEXT = ("Typography is the craft of arranging type so that written language is " "legible, readable and pleasing when displayed. The size of the letters, " "the length of each line and the space between the lines all work together, " "and changing one of them changes the feel of the others.") SPECS = [ # (label, font, size px, measure px, line-height multiplier) ("A: wide and tight", "Arial", 14, 900, 1.1), ("B: balanced", "Georgia", 18, 560, 1.5), ("C: narrow and airy", "Georgia", 22, 220, 1.9), ] def load(name): font = TTFont(FONT_DIR / FONTS[name]) return font.getBestCmap(), font["hmtx"], font["head"].unitsPerEm def wrap(text, width_of, measure): lines, current = [], "" for word in text.split(): trial = (current + " " + word).strip() if width_of(trial) <= measure or not current: current = trial else: lines.append(current) current = word lines.append(current) return lines def verdict(avg_chars, line_height): notes = [] if avg_chars > 80: notes.append("lines too long") elif avg_chars < 40: notes.append("lines too short") else: notes.append("line length ok") if line_height < 1.3: notes.append("leading tight") elif line_height > 1.8: notes.append("leading loose") else: notes.append("leading ok") return ", ".join(notes) print(f"{'spec':<22}{'lines':>6}{'avg chars':>11} verdict") for label, font_name, size, measure, lh in SPECS: cmap, hmtx, upm = load(font_name) width_of = lambda s: sum(hmtx[cmap[ord(c)]][0] for c in s) / upm * size lines = wrap(TEXT, width_of, measure) avg = sum(len(l) for l in lines) / len(lines) print(f"{label:<22}{len(lines):>6}{avg:>11.1f} {verdict(avg, lh)}") Output on the machine this course was written on (Windows 11, Python 3.14.0, fontTools 4.63.0): spec lines avg chars verdict A: wide and tight 2 136.0 lines too long, leading tight B: balanced 4 67.5 line length ok, leading ok C: narrow and airy 14 18.6 lines too short, leading loose What to take from it -------------------- * Spec A puts the whole paragraph on 2 lines of 136 characters: far past the guideline, and the tight leading makes it worse. * Spec C breaks the same paragraph into 14 lines of about 19 characters. The big, loosely spaced text falls apart. * Spec B (18px Georgia, 560px, 1.5) lands in range. The limits 40 to 80 and 1.3 to 1.8 are rules of thumb (check), not laws. * The wrapping is a greedy estimate using glyph advance widths only; a browser also applies kerning and may hyphenate, so its line counts can differ a little.