用 jupyter-book 构建可执行 NLTK 教程
解读
面试官抛出这道题,不是让你背命令,而是考察三条硬核能力:
- 能否把“教学-科研-工程”三场景打通,让教程既可交互执行又可离线交付;
- 是否熟悉国内镜像、合规语料与版权红线,避免“跑不通、下不动”的尴尬;
- 能否用 CI/CD 把“写书-构建-部署”做成一键流水线,让老板当天就能看到在线预览。
答得越像“开箱即用的产品”,越能拉开与普通候选人的差距。
知识点
- jupyter-book 核心栈:
_config.yml、_toc.yml、MyST Markdown、sphinx-exercise 插件。 - NLTK 国内加速:
nltk.data.path追加清华镜像https://mirrors.tuna.tsinghua.edu.cn/nltk/data/;强制离线包打包为nltk_data.zip随 repo 发布,避免现场下载超时。 - 可执行性保证:
- 每页顶部插入
%%capture捕获下载日志,防止 CI 因输出过长被杀; - 用
jupyterbook-latex生成 PDF 时,exclude 交互式 widget 防止 LaTeX 报错。
- 每页顶部插入
- 合规与版权:对“微博情感语料”、“人民日报 1998” 等国内常用语料,必须在附录写明授权链;若仅用于教学,采用 CC-NC 版本并在
_config.yml声明“禁止商业用途”。 - 一键部署:GitHub Actions 缓存
nltk_data目录,构建≤3 min;Gitee Pages 同步解决国内访问慢的问题,域名备案用公司主体,ICP 号写在页脚。
答案
步骤 1:项目骨架
mkdir nltk-tutorial && cd nltk-tutorial
python -m venv .venv && source .venv/bin/activate
pip install -U jupyter-book nltk scikit-learn matplotlib
步骤 2:国内镜像初始化 NLTK 数据
import nltk, os, zipfile, requests
mirror = "https://mirrors.tuna.tsinghua.edu.cn/nltk/data/"
pkgs = ['punkt', 'stopwords', 'averaged_perceptron_tagger']
for p in pkgs:
nltk.download(p, download_dir='./nltk_data', quiet=True)
把 nltk_data 目录提交到 git,并在 _config.yml 加:
repository:
url: https://github.com/yourname/nltk-tutorial
launch_buttons:
binderhub_url: https://gitee.com/openbayes
步骤 3:构建目录 _toc.yml
format: jb-book
root: intro
chapters:
- file: ch01-tokenize
- file: ch02-pos
- file: ch03-sentiment
- file: appendix-license
步骤 4:确保每章可执行
在 ch01-tokenize.md 顶部写:
---
jupytext:
kernelspec:
display_name: Python 3
name: python3
execution:
timeout: 60
---
步骤 5:CI/CD
.github/workflows/book.yml 关键片段:
- name: Cache NLTK data
uses: actions/cache@v3
with:
path: nltk_data
key: nltk-${{ hashFiles('nltk_data/**') }}
- name: Build book
run: jupyter-book build .
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: _build/html
步骤 6:国内合规
在 appendix-license.md 用 红色警告块 写明:
本教程使用的“人民日报 1998 分词语料”仅授权教学用途,严禁商业传播;若需商用,请联系北京大学计算语言学研究所重新获取授权。
完成后,面试官现场扫码即可打开教程,手机端 3 秒加载,Binder 点击直接跑通情感分析,无需任何额外配置。
拓展思考
- 如果企业内网完全隔离外网,可把 jupyter-book 构建成 离线静态包(
jupyter-book build --builder dirhtml),用 Nginx 容器镜像nginx:alpine内置,体积 < 80 MB,实现“U 盘级”交付。 - 教程迭代频繁时,用 pre-commit 钩子 自动跑
jupyter-book build --warningiserror --keep-going,保证任何 Markdown 语法或代码错误无法进入主干分支,降低维护成本。 - 面试加分项:展示 “交互-视频-测验”三位一体——在 MyST 里嵌入
ipywidgets做实时词云,用sphinx-togglebutton折叠答案,再接入 雨课堂 或 飞书妙记 生成学习数据看板,让 HR 一眼看到“培训数字化”潜力。