Code open-ended survey answers into themes and count them
Asking an AI to count survey themes directly leaves no per-response tags. Map each response to one codebook theme in CSV, then check IDs and aggregate.
After collecting hundreds of free-form survey responses, teams need quantitative breakdowns showing how many comments fall under each theme. Manually tagging rows in Excel takes hours. Passing the raw comments to an AI with an open prompt asking "count the issues by theme" yields untrustworthy totals.
Language models often invent plausible proportions while miscounting totals or quietly omitting ambiguous comments. Because the model outputs only aggregated figures rather than an explicit 1:1 mapping for every row, auditors cannot verify which comments were grouped into which category.
To get reliable counts, avoid delegating arithmetic to the model. Instruct the AI to output a clean CSV mapping each survey ID to a predefined theme code. Then recalculate totals using a verification script or a spreadsheet pivot table, confirming that the output row count matches the input row count. The same cross-checking principle applies to recomputing AI-stated numbers from CSV data.
[1] Prepare the raw survey text. Below is a sample from 120 synthetic cafeteria satisfaction responses. Personal data has been omitted, and each row contains an ID and feedback separated by a tab.
R001 I wish there was at least one vegetarian or salad-focused light meal option every day.R002 Western and snack station menus repeat too often. We need more weekly diet variety.…R029 Soups and stews are generally too salty. Please lower the sodium level slightly.…R055 During peak lunch hour at noon, the line is so long that waiting alone takes 15 minutes.…R080 Trays sometimes remain slippery with leftover grease that was not cleaned properly.…R101 Out-of-pocket costs rose after meal subsidy adjustments this year, feeling burdensome.…R120 Remote workers need an option to spend their meal allowance on meal kit deliveries.[2] Observe the limitations of asking for direct counts. When prompted with a simple request to count categories across 120 responses, the model produces a text table.
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/fail_count.en.prompt.txt > run/fail_count.en.out.txt| Theme | Responses | Count | Share ||---|---|---|---|| 1. Menu variety and dietary options (vegetari … | R001-R028 | 28 | 23.3% || 2. Food quality and taste (too salty, sweet o … | R029-R054 | 26 | 21.7% || 3. Crowding, queues and seating/facilities (p … | R055-R079 | 25 | 20.8% || 4. Hygiene and cleanliness (dirty utensils, t … | R080-R100 | 21 | 17.5% || 5. Pricing, operating hours, payment and serv … | R101-R120 | 20 | 16.7% || **Total** | | **120** | **100%** |In this block a … at the end of a theme cell marks a cut made here to fit the page; the model's cells were longer.
The total is 120 and, because this sample's IDs are grouped by theme, the model answered with ID ranges such as R001-R028. The table leaves no per-response tag to load into a spreadsheet, and its counts differ from the coded result in steps 4 to 6 (for example Wait_Time_Seating 24 and Pricing_Operations 17 there). With no answer key, this data cannot say which side is right; only the per-ID tags can be traced back. Shuffled IDs were not tested.
[3] Construct a structured coding prompt. Following OpenAI prompt engineering guidance, define an explicit taxonomy (codebook) and demand machine-readable CSV output.
Classify (code) the open-ended cafeteria survey responses based on the codebook below. ## Codebook (Theme Taxonomy)- Menu_Variety: Menu rotation, vegan/salad/special meal options, dietary diversity- Food_Quality: Seasoning (salty/sweet), cooking doneness, meat texture, temperature, greasiness- Wait_Time_Seating: Serving/tray return queues, peak-hour congestion, seat shortage, layout bottlenecks- Hygiene_Cleanliness: Dishware cleanliness, table sanitization, odors/ventilation, sanitation standards- Pricing_Operations: Meal subsidy/pricing, operating hours (breakfast/dinner), ticket app/payment, notices- Other: Feedback that does not fit into the five categories above ## Rules1. Assign exactly one primary theme code to each response.2. Include all 120 response IDs (R001 through R120) without missing or duplicating any rows.3. Output strictly raw CSV data with no conversational filler, introduction, or explanation.4. The first line of the CSV must be the header: `ID,Theme`. <survey_responses>{survey_responses}</survey_responses>[4] Execute the prompt to retrieve raw CSV mappings. The runs were made from an empty folder outside the repository, because instruction files in parent folders are read when you run inside a project.
$ claude -p --model claude-sonnet-5-5 --max-turns 1 --tools "" --setting-sources "" --strict-mcp-config < run/code_survey.en.prompt.txt > run/code_survey.en.1.out.txtID,ThemeR001,Menu_VarietyR002,Menu_Variety…R029,Food_Quality…R055,Wait_Time_Seating…R080,Hygiene_Cleanliness…R101,Pricing_Operations…R110,OtherR111,Pricing_OperationsR112,Food_Quality…R116,Other…R120,Pricing_OperationsThe output returns 120 rows mapped to single codes. The model flagged outlier feedback such as R110 (transitioning to biodegradable takeout containers) and R116 (adding a nutritionist feedback desk) under Other.
[5] Run a verification script to validate IDs and aggregate counts. The script checks that:
- the IDs in the result CSV match the survey IDs 1:1 (no ID outside the survey, no duplicate, no missing ID, same row count)
- the header is
ID,Themeand every line has 2 columns - every theme is one of the 6 codebook themes
It does not check whether the model put each response under the right theme; it only checks that IDs and codes have the right form.
#!/usr/bin/env python3"""usage: python check_coding_en.py <survey.txt> <result.csv>"""import sys, csvfrom collections import Counter THEMES = {"Menu_Variety", "Food_Quality", "Wait_Time_Seating", "Hygiene_Cleanliness", "Pricing_Operations", "Other"}expected = [l.split("\t")[0].strip() for l in open(sys.argv[1], encoding="utf-8") if l.strip()]lines = [l.strip() for l in open(sys.argv[2], encoding="utf-8") if l.strip()]rows = list(csv.reader(lines))errors, seen, dups, counts = [], set(), set(), Counter() if not rows or [c.strip() for c in rows[0]] != ["ID", "Theme"]: errors.append(f"header is not ID,Theme: {rows[:1]}")for n, row in enumerate(rows[1:], start=2): if len(row) != 2: errors.append(f"line {n}: {len(row)} columns"); continue rid, theme = row[0].strip(), row[1].strip() if rid not in expected: errors.append(f"line {n}: ID {rid} is not in the survey") if rid in seen: dups.add(rid) seen.add(rid) if theme not in THEMES: errors.append(f"line {n}: theme {theme!r} is not in the codebook ({rid})") counts[theme] += 1if dups: errors.append(f"{len(dups)} duplicate IDs: {sorted(dups)[:5]}")missing = set(expected) - seenif missing: errors.append(f"{len(missing)} missing IDs: {sorted(missing)[:5]}")if len(expected) != len(set(expected)): errors.append("the survey file repeats an ID")if sum(counts.values()) != len(expected): errors.append(f"row count: {len(expected)} in the survey, {sum(counts.values())} in the result") if errors: print(f"[FAIL] {len(errors)} errors:") for e in errors: print(" -", e) sys.exit(1)print(f"[OK] IDs match the {len(expected)} survey rows 1:1 (missing 0, duplicates 0, themes outside the codebook 0)")for t, c in counts.most_common(): print(f" - {t}: {c} ({c / len(expected) * 100:.1f}%)")[6] Validate the real run. Run 1 matches the 120 survey rows, and run 2 passed the ID check too, but its theme counts differ from run 1 (because of R109: Pricing_Operations 16 instead of 17, Other 3 instead of 2).
$ python run/check_coding_en.py run/survey_120.en.txt run/code_survey.en.1.out.txt[OK] IDs match the 120 survey rows 1:1 (missing 0, duplicates 0, themes outside the codebook 0) - Menu_Variety: 28 (23.3%) - Food_Quality: 27 (22.5%) - Wait_Time_Seating: 24 (20.0%) - Hygiene_Cleanliness: 22 (18.3%) - Pricing_Operations: 17 (14.2%) - Other: 2 (1.7%)Four hand-edited fault files were tried, and all exit with code 1: bad_missing.en.csv (R045 deleted), bad_dup.en.csv (R010 repeated), bad_unknown.en.csv (a theme outside the codebook) and bad_swap.en.csv (one row deleted and another repeated, so the row count stays 120 but the check still fails). The last one (not model output):
$ python run/check_coding_en.py run/survey_120.en.txt run/bad_swap.en.csv[FAIL] 2 errors: - 1 duplicate IDs: ['R010'] - 1 missing IDs: ['R045']The Korean codebook lists "noise" under hygiene, while this English codebook does not, so the same noise comment (R078) went to hygiene in the Korean run 1 and to Wait_Time_Seating in the English run 1. Keep that difference in mind when comparing counts across the two editions.
[7] Inspect borderline cases and perform spot checks. Comparing the first run with an identical second run (code_survey.en.2.out.txt) revealed exactly 1 discrepancy out of 120 rows:
R109: categorized asPricing_Operationsin run 1, andOtherin run 2
Examining the comment explains the shift:
R109: "Cafeteria satisfaction survey results should be shared transparently on the company intranet."
Because transparency requests touch internal operations yet do not directly concern meal logistics, model classification can fluctuate across invocations.
To stabilize borderline items, you could add a disambiguation rule to the codebook (for example: "route general communication requests to Operations"). A run with that rule was not tested here. Before finalizing a report, read a sample of up to 5 comments per category yourself (all of them for Other, which has only 2 or 3 rows in these outputs) and compare the text with its tag.