附录 A:CleanList 第一版完整规格示例
第 32 / 35 篇 课程状态:读取中 上次阅读位置保存在当前浏览器
A1. Problem Statement
People who prepare contact CSV files for newsletters, outreach, or event follow-up often need to remove duplicate records before importing them elsewhere. They can use spreadsheet software, but formatting inconsistencies and privacy concerns make this repetitive and error-prone.
A2. V1 Promise
Remove duplicate CSV rows by a selected column, entirely in the browser, with no sign-up and no file upload.
A3. In Scope
- Single CSV upload
- Header detection
- Column selection
- Trim + lowercase normalization for comparison
- Keep first matching record
- Result summary
- Download cleaned CSV
A4. Out of Scope
- Accounts
- Cloud history
- Team features
- Billing
- Multiple-file merge
- AI cleanup
- CRM integration
- Automatic email validation
- Server upload
- API
A5. Acceptance Criteria
- User can complete the core path on current desktop and mobile browsers.
- File contents are not sent to application servers.
- Quoted CSV fields are parsed correctly.
- Unicode text survives round-trip.
- User sees original row count, duplicate count, output row count.
- User can download a valid CSV.
- Invalid input produces a readable error instead of silent failure.
A6. 跟着做:从CSV输入到可核对的下载结果
本书完整ZIP另附 cleanlist-demo/(HTML、JS、机器测试、README)及 fixtures/(模拟CSV)。第一次做网站时先把这条主路径真实走通,不要只读技术清单。
- 解压完整ZIP。打开
LEARNING_START_HERE.md。用浏览器双击cleanlist-demo/index.html;若浏览器阻止本地脚本,已安装Python时可在该目录运行python -m http.server 8000,浏览器访问http://localhost:8000。 - 在你没看参考答案前,预测
fixtures/cleanlist_normal_input.csv的行数变化:有4条,按Email忽略大小写和前后空格去重,应该剩下几条?写在练习本上。 - 选择这个样本CSV,选择
Email列,点击“检查并生成”。示例预期显示原始4、重复2、保留2。下载后与fixtures/cleanlist_normal_expected.csv比较。 - 使用
fixtures/cleanlist_quoted_input.csv,预期原始3、重复1、保留2;检查带中文和引号内逗号的字段没有损坏。 - 在模拟CSV副本里故意留下一个空Email,观察错误解释与下载按钮是否关闭;再把一个单元格设置为
=2+3,核对是否拒绝导出,而不是悄悄改写数据。 - 记录浏览器、日期、原始输入、预期、观察结果、FAIL及复现步骤。若某一步失败,返回
cleanlist-demo/README.md查“限制和数据说明”,不要直接改大段代码。
你应学到三件事:第一,能运行≠规则正确;第二,单测PASS≠浏览器与手机都PASS;第三,模拟数据PASS≠真人用户愿意用,更不等于有正式域名、HTTPS或隐私法律合规。 教学样例最大1MB/2000行/40列,不接受空去重键、危险公式单元格、Excel工作簿或不合法CSV;这些是明确的范围限制,而非通用CSV处理器的承诺。想发布到互联网,仍要完成第9~16章的独立检查,不能只复制样例就宣称生产Ready。
A7. 读者的“失败恢复收据”
每次失败只填六项:具体输入→期望→实际输出/错误→定位在哪一层→最小修复→相同输入的复测结果。成功时也要记录未测的条件,如 MOBILE=NOT_RUN、REAL_READER=NOT_RUN。如果只在一台电脑上跑通,就写“本地样例主路径完成”;不要给第23章真实上线验收打勾。
A8. 只拿到 P01 课程也能动手:单文件离线 CleanList
读者入口:如果你是在 P01 课程中看到这页,不需要先取得本书的完整 ZIP,也不需要安装 Node.js、Python、框架、数据库或申请任何账号。本节将原有三文件教学网站的 HTML、 核心逻辑和界面控制打包为一个文件(源代码相同,不另写一套简化算法)。
- 在电脑上打开记事本或纯文本编辑器,创建新文件;只复制下面一整个
html代码块的内容,不要复制开头、结尾的三个反引号。 - 保存为
cleanlist.html,编码选 UTF-8。Windows 记事本保存时选择“所有文件”,避免变成cleanlist.html.txt。双击这个 HTML 用浏览器打开;浏览器地址可显示file:///.../cleanlist.html,无需互联网。 - 再把下方第一段 CSV 内容复制进另一个纯文本文件,保存为
cleanlist_normal_input.csv(UTF-8);第二段另存cleanlist_quoted_input.csv。这两份都是虚构教学数据,不要使用真实客户邮箱。 - 在页面选择正常 CSV,去重依据选
Email,点击“检查并生成”。预期 原始4行、重复2行、保留2行;下载并用文本编辑器核对只剩 Alice 和 Bob 的首条记录。 - 使用第二份带引号与中文的 CSV,预期 原始3行、重复1行、保留2行,逗号仍保留在引号内。
- 复制一份正常 CSV,把某行的 Email 清空:应报错且不能下载;再把任意单元格值改成
=2+3:应阻止导出。每次故意失败后再次打开有效样本,确认能恢复。
安全边界:这只是为了独立完成阅读任务而提供的离线教学代码,拒绝 CSV 公式前缀、无效行和大于 1 MB 的输入,但不保证覆盖全部 CSV 格式或安全威胁。正常使用与生产部署不是一回事。原工程和完整代码测试、更多失败样本仍在完整教材 ZIP 中。
A8.1 复制以下完整 HTML,保存为 cleanlist.html
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CleanList | 本地 CSV 去重教学样例</title>
<meta name="description" content="本地 CSV 去重的教学样例;无账号,无文件服务器上传。仅用于教材训练。">
<meta name="robots" content="noindex, nofollow">
<style>
:root { font-family: system-ui, sans-serif; color: #192b22; background: #f7fbf9; line-height: 1.55; }
* { box-sizing: border-box; }
main { max-width: 640px; margin: 5vh auto; padding: 24px; background: white; border: 1px solid #d5e7de; border-radius: 14px; }
h1 { font-size: 1.65rem; margin: 0 0 .75rem; }
label { display:block; margin-top: 20px; font-weight: 650; }
input, select, button { font: inherit; padding: .7rem; max-width:100%; }
input, select { width: 100%; margin-top: 6px; border: 1px solid #879c90; border-radius: 7px; }
button { margin-top: 18px; background: #07884f; color: #fff; border:0; border-radius: 8px; font-weight:600; }
button:disabled { opacity: .55; cursor:not-allowed; }
a#download { display: inline-block; margin-top: 16px; color:#065f3c; font-weight: 650; }
a#download[hidden] { display: none; }
:focus-visible { outline: 3px solid #db9330; outline-offset: 3px; }
#error { color: #8a1b18; font-weight:650; margin-top: 14px; }
#summary { padding-top: 12px; }
.limits { border-left: 3px solid #07884f; padding-left: 12px; margin-top: 22px; }
</style>
</head>
<body>
<main>
<h1>CleanList · 本地 CSV 去重</h1>
<p>一步一步尝试教材示例:选择文件 → 选择去重列 → 检查结果 → 下载。无需登录。</p>
<label for="csv-file">1. 选择 CSV 文件(最大 1 MB)</label>
<input id="csv-file" type="file" accept=".csv,text/csv">
<label for="key-column">2. 去重依据列</label>
<select id="key-column" disabled aria-describedby="key-note"></select>
<p id="key-note">对所选列去掉前后空格、忽略大小写,保留第一次出现的整行;不改变保留行的原始内容。</p>
<button id="run" type="button" disabled>3. 检查并生成</button>
<div id="error" role="alert" aria-live="assertive"></div>
<p id="info" role="status" aria-live="polite"></p>
<p id="summary" role="status" aria-live="polite"></p>
<a id="download" hidden>4. 下载结果 CSV</a>
<section class="limits" aria-label="限制和数据说明">
<strong>教学边界</strong>
<p>仅支持 UTF-8、英文逗号分隔、带表头、最多 2000 行与 40 列的 CSV。空白去重键、空白行、格式损坏或可疑公式单元格会中止导出。不是通用的 Excel 或邮件校验器。</p>
<p>本页示例代码不发起网络请求,也不读取文件以外的数据;正式发布后,托管服务仍可能产生常规访问日志。</p>
</section>
</main>
<script>
/* CleanList teaching sample: intentionally limited, deterministic, no network. */
(function (root, factory) {
const api = factory();
if (typeof module === 'object' && module.exports) module.exports = api;
else root.CleanListCore = api;
})(typeof globalThis !== 'undefined' ? globalThis : this, function () {
'use strict';
const MAX_FILE_BYTES = 1024 * 1024;
const MAX_RECORDS = 2000;
const MAX_COLUMNS = 40;
const MAX_FIELD_LENGTH = 20000;
function parseCSV(source) {
if (typeof source !== 'string') throw new Error('CSV 内容必须是文本。');
const text = source.replace(/^\uFEFF/, '');
if (!text.trim()) throw new Error('文件为空。');
const rows = [];
let row = [], cell = '', quoted = false, afterQuote = false;
function finishCell() {
if (cell.length > MAX_FIELD_LENGTH) throw new Error('单元格过长,不支持此文件。');
row.push(cell); cell = ''; afterQuote = false;
if (row.length > MAX_COLUMNS) throw new Error('超过支持的列数。');
}
function finishRow() {
finishCell();
// Empty last physical line is not a record; blank row in the middle is.
if (row.every(x => x === '')) throw new Error('发现空白数据行,请先清理文件。');
rows.push(row); row = [];
if (rows.length - 1 > MAX_RECORDS) throw new Error('超过本示例支持的 2000 行。');
}
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (quoted) {
if (ch === '"' && text[i + 1] === '"') { cell += '"'; i++; }
else if (ch === '"') { quoted = false; afterQuote = true; }
else { cell += ch; }
} else if (afterQuote) {
if (ch === ',') finishCell();
else if (ch === '\n' || ch === '\r') {
finishRow(); if (ch === '\r' && text[i + 1] === '\n') i++;
} else throw new Error('引号结束后出现意外字符。');
} else if (ch === ',') finishCell();
else if (ch === '\n' || ch === '\r') {
finishRow(); if (ch === '\r' && text[i + 1] === '\n') i++;
} else if (ch === '"') {
if (cell !== '') throw new Error('引号位置错误,请检查 CSV。');
quoted = true;
} else cell += ch;
if (cell.length > MAX_FIELD_LENGTH) throw new Error('单元格过长,不支持此文件。');
}
if (quoted) throw new Error('CSV 引号未闭合。');
if (cell !== '' || row.length || afterQuote) finishRow();
if (rows.length < 2) throw new Error('需要表头和至少一行数据。');
const width = rows[0].length;
if (rows[0].some(x => !x.trim()) || new Set(rows[0].map(x => x.trim().toLowerCase())).size !== width) {
throw new Error('表头不能为空,也不能重复。');
}
for (let i = 1; i < rows.length; i++) if (rows[i].length !== width) {
throw new Error(`第 ${i + 1} 行列数与表头不一致。`);
}
return rows;
}
function checkSafeCells(rows) {
// Fail closed; deliberately does not silently rewrite customer data.
for (let r = 0; r < rows.length; r++) {
for (let c = 0; c < rows[r].length; c++) {
const value = rows[r][c];
if (/^[\s\uFEFF\u200B\u200E\u200F]*[=+\-@]/u.test(value) || /[\x00-\x08\x0B\x0C\x0E-\x1F]/.test(value)) {
throw new Error(`第 ${r + 1} 行第 ${c + 1} 列有潜在公式或控制字符;为保护导出安全,本示例停止处理。`);
}
}
}
}
function dedupeRows(rows, keyColumn) {
if (!Array.isArray(rows) || !rows.length || !Number.isInteger(keyColumn) || keyColumn < 0 || keyColumn >= rows[0].length) {
throw new Error('请选择一个有效的去重列。');
}
checkSafeCells(rows);
const seen = new Set(), output = [rows[0]], firstRows = [];
for (let i = 1; i < rows.length; i++) {
const key = rows[i][keyColumn].trim().toLowerCase();
if (!key) throw new Error(`第 ${i + 1} 行的去重列为空,请先修正。`);
if (!seen.has(key)) { seen.add(key); output.push(rows[i]); firstRows.push(i + 1); }
}
return { rows: output, inputCount: rows.length - 1, outputCount: output.length - 1,
duplicates: rows.length - output.length, firstRows };
}
function csvCell(cell) {
const v = String(cell);
return /[",\r\n]/.test(v) ? '"' + v.replace(/"/g, '""') + '"' : v;
}
function exportCSV(rows) { return '\uFEFF' + rows.map(row => row.map(csvCell).join(',')).join('\r\n') + '\r\n'; }
function processCSV(text, keyColumn) {
const result = dedupeRows(parseCSV(text), keyColumn);
return { ...result, csv: exportCSV(result.rows) };
}
return { MAX_FILE_BYTES, MAX_RECORDS, parseCSV, dedupeRows, exportCSV, processCSV };
});
</script>
<script>
'use strict';
(() => {
const core = window.CleanListCore;
const input = document.querySelector('#csv-file');
const keySelect = document.querySelector('#key-column');
const run = document.querySelector('#run');
const info = document.querySelector('#info');
const error = document.querySelector('#error');
const summary = document.querySelector('#summary');
const download = document.querySelector('#download');
let rows = null, currentName = '';
let objectURL = null;
const clearDownload = () => {
download.hidden = true;
download.removeAttribute('href');
if (objectURL) URL.revokeObjectURL(objectURL);
objectURL = null;
};
const fail = msg => { error.textContent = msg; info.textContent = ''; summary.textContent = ''; clearDownload(); };
input.addEventListener('change', async () => {
rows = null; keySelect.replaceChildren(); keySelect.disabled = true; run.disabled = true;
error.textContent = ''; info.textContent = ''; summary.textContent = ''; clearDownload();
const file = input.files && input.files[0];
if (!file) return;
if (!/\.csv$/i.test(file.name)) return fail('请选择 .csv 文件。');
if (file.size > core.MAX_FILE_BYTES) return fail('文件大于 1 MB,此教学示例不处理。');
try {
const utf8 = new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer());
rows = core.parseCSV(utf8); currentName = file.name;
// Do not validate an arbitrary first column: the reader may choose another key.
rows[0].forEach((h, i) => {
const opt = document.createElement('option'); opt.value = String(i); opt.textContent = h;
keySelect.append(opt);
});
const email = rows[0].findIndex(h => h.trim().toLowerCase() === 'email');
keySelect.value = String(email >= 0 ? email : 0);
keySelect.disabled = false; run.disabled = false;
info.textContent = `已读取 ${rows.length - 1} 行数据。请选择去重列,再点击“检查并生成”。`;
} catch (e) { rows = null; fail(e.message || '无法读取文件。'); }
});
run.addEventListener('click', () => {
error.textContent = ''; summary.textContent = ''; clearDownload();
try {
if (!rows) throw new Error('请先选择有效 CSV 文件。');
const result = core.dedupeRows(rows, Number(keySelect.value));
const blob = new Blob([core.exportCSV(result.rows)], { type: 'text/csv;charset=utf-8' });
objectURL = URL.createObjectURL(blob);
download.href = objectURL;
download.download = currentName.replace(/\.csv$/i, '') + '-clean.csv';
download.hidden = false;
summary.textContent = `原始 ${result.inputCount} 行,去掉重复 ${result.duplicates} 行,保留 ${result.outputCount} 行。请先确认去重规则,再下载。`;
info.textContent = '处理完成:文件只在本次浏览器页面中处理,不会由本示例主动上传。';
} catch (e) { fail(e.message || '处理失败。'); }
});
keySelect.addEventListener('change', () => { clearDownload(); summary.textContent = ''; });
})();
</script>
</body>
</html>
A8.2 第一份模拟输入:cleanlist_normal_input.csv
Email,Name,City
[email protected],Alice,Tokyo
[email protected] ,Alice 2,Paris
[email protected],Bob,New York
[email protected],Bobby,London
A8.3 第二份模拟输入:cleanlist_quoted_input.csv
Email,Name,Note
[email protected],王小明,"Works with CSV, Excel"
[email protected] ,Sara,"Plan A, revised"
[email protected],Sara Again,"Leave, then return"
A8.4 亲手验收并记录失败
| 任务 | 预期 | 你的实际结果 | 状态 |
|---|---|---|---|
| 正常CSV Email 去重 | 4 → 2 | 自行填写 | NOT_RUN |
| 含引号/中文CSV | 3 → 2 | 自行填写 | NOT_RUN |
| 空白 Email | 拒绝处理,无下载 | 自行填写 | NOT_RUN |
| 公式前缀 =2+3 | 拒绝导出,无下载 | 自行填写 | NOT_RUN |
| 打开失败后重试正确文件 | 能重新处理 | 自行填写 | NOT_RUN |
如果你保存后双击打开只看到一大段 HTML 文字,先检查文件名是否意外变成 .txt;如果文件选择按钮无法使用,换用最新版桌面浏览器,并先确保浏览器没有屏蔽本地文件读取。如果离线测试通过,却无法部署到公网,应返回第9~11章检查 Git、构建入口和托管平台设置,不要把本地测试当作正式网站上线证据。