Skip to content
v0.1.4latest release159 skills5 categories7 sub-categories303 tested scripts468 reference docsContact us

decodable_check.py

Helper script for adult-literacy-esl-lesson-builder · 110 lines

Languages, Linguistics & Translation / Language Teachingv1.0.0Updated OCT 25 20262 references1 script
scripts/decodable_check.py
#!/usr/bin/env python3
"""Check how decodable a reading text is for adult literacy learners, given the letter-sound patterns taught.

A word is decodable when it can be split entirely into taught graphemes (single letters or patterns such as sh,
ch, th, ck, ee, ai). A common digraph that has not been taught makes the word non-decodable even if its letters
were taught singly (shop needs "sh", not s + h). Sight words learners have been taught as wholes (the, I, to,
is...) count as readable. Everything else is listed with the untaught part, so the teacher can swap the word or
pre-teach it.

Usage:
    python decodable_check.py text.txt --taught s a t p i n m d g o c k ck e u r h b f l --sight the I to is a
    python decodable_check.py text.txt --taught-file taught.txt --sight-file sight.txt --min 90

Exit codes: 0 at or above --min % readable (default 90), 1 below, 2 read error or nothing taught.
"""

import argparse
import re
import sys
from collections import Counter

DIGRAPHS = ["tch", "igh", "air", "ear", "ure", "sh", "ch", "th", "ph", "wh", "ck", "ng", "qu", "ee", "ea", "oa", "ai",
            "ay", "oo", "ou", "ow", "oi", "oy", "ar", "or", "er", "ir", "ur", "aw", "ew"]


def untaught_digraph(word, graphemes):
    return next((d for d in DIGRAPHS if d in word and d not in graphemes), None)


def split(word, graphemes):
    """Return a split into taught graphemes, or None. Longest graphemes are tried first."""
    if untaught_digraph(word, graphemes):
        return None
    best = {0: []}
    for i in range(len(word)):
        if i not in best:
            continue
        for g in graphemes:
            if word.startswith(g, i) and i + len(g) not in best:
                best[i + len(g)] = best[i] + [g]
    return best.get(len(word))


def first_gap(word, graphemes):
    d = untaught_digraph(word, graphemes)
    if d:
        return d
    i = 0
    while i < len(word):
        g = next((g for g in graphemes if word.startswith(g, i)), None)
        if not g:
            return word[i]
        i += len(g)
    return ""


def words_from(args_list, path):
    items = list(args_list or [])
    if path:
        items += open(path, encoding="utf-8").read().split()
    return items


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("text", help="text file, or - for stdin")
    ap.add_argument("--taught", nargs="*", help="graphemes taught so far")
    ap.add_argument("--taught-file")
    ap.add_argument("--sight", nargs="*", help="sight words taught")
    ap.add_argument("--sight-file")
    ap.add_argument("--min", type=float, default=90, help="minimum %% readable (default 90)")
    a = ap.parse_args()
    try:
        text = (sys.stdin if a.text == "-" else open(a.text, encoding="utf-8")).read()
        graphemes = sorted({g.lower() for g in words_from(a.taught, a.taught_file)}, key=len, reverse=True)
        sight = {w.lower() for w in words_from(a.sight, a.sight_file)}
    except OSError as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    if not graphemes:
        print("error: give the taught graphemes with --taught or --taught-file", file=sys.stderr)
        return 2
    tokens = [w.lower() for w in re.findall(r"[A-Za-z']+", text)]
    if not tokens:
        print("error: no words in the text", file=sys.stderr)
        return 2
    bad, ok_sight = Counter(), 0
    for w in tokens:
        clean = w.replace("'", "")
        if w in sight or clean in sight:
            ok_sight += 1
        elif not split(clean, graphemes):
            bad[clean] += 1
    readable = 100 * (len(tokens) - sum(bad.values())) / len(tokens)
    print(f"{len(tokens)} words: {readable:.0f}% readable ({ok_sight} sight-word tokens)")
    if bad:
        print("Not yet decodable (untaught part):")
        for w, n in bad.most_common():
            print(f"  {w}{f' x{n}' if n > 1 else ''}  ['{first_gap(w, graphemes)}']")
    gaps = Counter(first_gap(w, graphemes) for w in bad.elements())
    if gaps:
        print("Most useful next patterns: " + ", ".join(f"{g} ({n})" for g, n in gaps.most_common(5)))
    ok = readable >= a.min
    print(f"{'OK' if ok else 'BELOW'}: target {a.min:g}% readable")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main())
More in Language Teaching

academic-english-eap-course-planner

Plan English for Academic Purposes (EAP) courses: pre-sessional, in-sessional, foundation, IELTS preparation and discipline-specific EAP, with syllabus strands (academic reading, lecture listening and note-taking, essay and report writing, paraphrase, summary and synthesis, referencing and plagiarism, seminars and presentations, academic vocabulary, critical thinking), a 10-week pre-sessional outline, exit assessment, IELTS-CEFR alignment and academic style (formality, hedging, cohesion, reporting verbs). Estimates study hours and weeks to close an IELTS gap from overall or per-skill scores (IELTS rounding, minimum per skill, priority skills, feasibility before a deadline), and checks learner texts for contractions, informal words with academic alternatives, unhedged claims, 'you', And/But/So starts, rhetorical questions and missing citations.

actfl-proficiency-curriculum-mapper

Map world language curricula to the ACTFL framework: proficiency levels (Novice, Intermediate, Advanced, Superior, Distinguished with sublevels), functions, contexts, text types and accuracy, proficiency vs performance, the three modes of communication (interpretive, interpersonal, presentational), the 5 Cs World-Readiness Standards, backward-designed thematic units with Integrated Performance Assessments, typical programme targets and FSI time estimates. Looks up approximate ACTFL-CEFR-ILR equivalences with what each level can do, and checks a unit map for missing modes, rehearsed skits mislabelled as interpersonal, translation or word lists as interpretive tasks, and units without an integrated performance assessment.

authentic-material-lesson-adapter

Turn authentic material (news articles, podcasts, videos, songs, menus, timetables, adverts, social media posts, forms, infographics) into language lessons by grading the task rather than the text. Selects texts for interest, relevance, exploitability, coverage, cultural load and rights; finds the 4-6 words to pre-teach, words to gloss on the page and words learners can ignore, plus names and cultural references to explain, with reading time by level; and builds a lesson shape (lead-in, pre-teach, gist or scanning, graded detail task, language focus on chunks and register, response) with task ideas per material type and level from A1 to C1. Covers copyright, fair dealing and fair use, Creative Commons and attribution.

can-do-statement-writer

Write and review can-do statements for language courses, units, lessons and learner self-assessment, CEFR or NCSSFL-ACTFL style: action (observable verb) + text or situation + level-specific conditions, learner ('I can') and descriptor ('Can') versions, progressions of one activity from A1 to C1, and coverage of reception, production, interaction and mediation. Includes a verb bank by mode and level and condition and text-type banks. Lints statements for teacher-centred phrasing, knowledge instead of use (learn, know, understand the passive), missing context, two skills in one statement, vague quality words, grammar items as outcomes, overlong statements and missing modes in a set.

cefr-aligned-syllabus-builder

Build language course syllabuses aligned to the CEFR (A1-C2, plus levels, Companion Volume 2020): entry and exit levels, guided learning hours and course length (with an L1-distance adjustment), syllabus type (topic, functional-notional, task-based, skills-based, multi-strand), unit-by-unit can-do outcomes, grammar from a core inventory by level, vocabulary, functions, pronunciation, balance of reception, production, interaction and mediation, recycling and assessment points. Checks a syllabus for units without can-do statements, core grammar for the level not covered, items above the course level, skills missing from most units and units with no vocabulary or functions.

classroom-management-for-esl-coach

Coach ESL/EFL teachers in classroom management: the instruction sequence (attention, group first, graded imperatives, demonstration, ICQs, hand out, start, check), ICQ examples, online instructions, routines for the first weeks (class agreement, L1 use, phones, lateness, homework, seating), strategies for L1 use in tasks, dominant and quiet learners, mixed levels, large classes, fast finishers, low motivation, disruptive young learners and teens, cultural expectations, classroom language to teach early and teacher presence. Checks planned instructions for length, missing ICQs, useless ICQs like 'Do you understand?', no demonstration, long sentences, filler and missing grouping or timing, and builds seating plans that keep named learners apart, seat learners who need the front, mix first languages and alternate stronger and weaker learners.