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

group_learners.py

Helper script for language-lesson-differentiation-planner · 108 lines

Languages, Linguistics & Translation / Language Teachingv1.0.0Updated OCT 25 20261 reference1 script
scripts/group_learners.py
#!/usr/bin/env python3
"""Group a mixed-level language class and flag learners who need extra support or extension.

CSV columns: name, level (CEFR like A2, B1+ or a 0-100 score), l1 (optional)

Modes:
  mixed  every group spans the class range (snake draft by level); same-L1 learners spread out where possible
  same   groups of similar level, for tiered tasks

Learners more than one CEFR level (or 25 points) from the class median are flagged.

Usage:
    python group_learners.py class.csv --size 4 --mode mixed
    python group_learners.py class.csv --size 3 --mode same

Exit codes: 0 groups printed, 2 read error or bad CSV.
"""

import argparse
import csv
import statistics
import sys

CEFR = {"A1": 1, "A2": 2, "B1": 3, "B2": 4, "C1": 5, "C2": 6}


def score(level):
    s = level.strip().upper()
    if s.rstrip("+-") in CEFR:
        return CEFR[s.rstrip("+-")] + (0.5 if s.endswith("+") else 0)
    return float(s)


def snake(learners, n_groups):
    groups = [[] for _ in range(n_groups)]
    for i, l in enumerate(learners):
        rnd, pos = divmod(i, n_groups)
        groups[pos if rnd % 2 == 0 else n_groups - 1 - pos].append(l)
    return groups


def spread_l1(groups):
    """Swap learners of equal level between groups when it reduces same-L1 clustering."""
    def clash(g):
        l1s = [x["l1"] for x in g if x["l1"]]
        return len(l1s) - len(set(l1s))
    for g in groups:
        for i, x in enumerate(g):
            if clash(g) == 0:
                break
            for h in groups:
                if h is g:
                    continue
                for j, y in enumerate(h):
                    if y["score"] == x["score"] and y["l1"] != x["l1"]:
                        before = clash(g) + clash(h)
                        g[i], h[j] = y, x
                        if clash(g) + clash(h) < before:
                            break
                        g[i], h[j] = x, y
                else:
                    continue
                break
    return groups


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("csv")
    ap.add_argument("--size", type=int, default=4, help="target group size (default 4)")
    ap.add_argument("--mode", choices=["mixed", "same"], default="mixed")
    a = ap.parse_args()
    try:
        with open(a.csv, newline="", encoding="utf-8-sig") as fh:
            rows = list(csv.DictReader(fh))
        learners = [{"name": r["name"].strip(), "level": r["level"].strip(), "score": score(r["level"]),
                     "l1": (r.get("l1") or "").strip()} for r in rows]
    except (OSError, KeyError, ValueError, AttributeError) as e:
        print(f"error: needs name and level columns with CEFR levels or scores ({e})", file=sys.stderr)
        return 2
    if len(learners) < 2:
        print("error: need at least two learners", file=sys.stderr)
        return 2
    learners.sort(key=lambda x: -x["score"])
    n = max(1, round(len(learners) / max(2, a.size)))
    if a.mode == "same":
        size = -(-len(learners) // n)
        groups = [learners[i:i + size] for i in range(0, len(learners), size)]
    else:
        groups = spread_l1(snake(learners, n))
    med = statistics.median(x["score"] for x in learners)
    gap = 1 if max(x["score"] for x in learners) <= 6 else 25
    print(f"{len(learners)} learners, median level {med:g}, {len(groups)} {a.mode} groups\n")
    for i, g in enumerate(groups, 1):
        members = ", ".join(f"{x['name']} ({x['level']}{', ' + x['l1'] if x['l1'] else ''})" for x in g)
        print(f"Group {i}: {members}")
    flags = [x for x in learners if abs(x["score"] - med) > gap]
    if flags:
        print()
    for x in flags:
        need = "extension / challenge role" if x["score"] > med else "support: scaffolds, pre-task time, partner"
        print(f"FLAG {x['name']} ({x['level']}) is far from the class median: {need}")
    return 0


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.

adult-literacy-esl-lesson-builder

Build lessons for adult ESL learners who are developing literacy (LESLLA learners: pre-literate, non-literate, semi-literate, literate in a non-Roman script): learner profiles and sensitive initial assessment, principles (oral language first, known to new, systematic phonics with adult-relevant text, repetition, classroom skills, respect for experience), a lesson routine (oral warm-up, review, new grapheme, blending, segmenting, decodable text, writing, functional literacy, Language Experience Approach), a phonics sequence for adults, sight words, functional literacy targets (forms, signs, medicine labels) and portfolio assessment. Checks whether a reading text is decodable with the letter-sound patterns and sight words taught so far, catching untaught digraphs, listing non-decodable words with the untaught part, and suggesting the most useful next patterns.

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.