如何将 Doccano 导出 JSONL 转换为 NLTK 可读的 ChunkedCorpus
解读
在国内工业界与科研场景中,Doccano 作为开源文本标注平台被广泛用于实体、关系、事件等序列标注任务。其标准导出格式为 JSONL,每行是一个 JSON 对象,内含 text、label 等字段。而 NLTK 的 ChunkedCorpusReader 只认两种格式:
- IOB2 三列文本:单词 POS IOB-标签
- 树括号 格式:
(NP 单词/pos) (VP 单词/pos)
因此,面试考点集中在“如何把 Doccano JSONL 中的实体偏移量转成 IOB2 或树括号,再让 NLTK 零成本加载”。面试官希望听到你:
- 能准确还原 IOB2 序列(处理嵌套、不连续、BIO 冲突)
- 能利用 NLTK 原生 API完成后续 ChunkedCorpusReader 封装
- 对中文空格缺失、Doccano 标签体系与 OntoNotes 差异有落地经验
知识点
- Doccano JSONL 字段解析:
text、label(start_offset, end_offset, label) - 中文字符级偏移与单词级偏移差异;
len("中文")在 Python 里为 2,需用utf-16码元对齐或jieba分词后重算 - IOB2 编码规则:
B-表片段首、I-表内部、O表外部;同类型实体相邻时必须 B I I… - NLTK ChunkedCorpusReader 构造函数:
ChunkedCorpusReader(root, fileids, sep='/', chunk_types=None, encoding='utf-8')
要求文件扩展名.pos或.chunk,内部按行读取,默认空格分隔三列 - 树括号与 IOB 互转:
nltk.chunk.conllstr2tree()、nltk.chunk.tree2conllstr() - 性能与内存:十兆级 JSONL 用惰性生成器逐行写盘,避免一次性载入
- 可维护性:写单元测试用
nltk.chunk.util.accuracy(chunker, gold)评估转换一致性
答案
下面给出可直接落地的 Python 脚本,兼容中文与英文,生成 NLTK 原生可读的 IOB2 文件;随后演示如何用 ChunkedCorpusReader 加载。假设 Doccano 导出文件为 doccano.jsonl,输出目录 data/chunked/。
import json, os, jieba, shutil
from pathlib import Path
def offsets_to_iob2(text, offsets, tokenizer=jieba.lcut):
"""
将 Doccano 偏移实体列表转成 IOB2 三列
:param text: 原始字符串
:param offsets: [(start, end, label), ...]
:param tokenizer: 分词器,英文可用 str.split
:return: list of (word, pos, iob)
"""
# 1. 分词并记录每个词的起止字符偏移
words = tokenizer(text)
word_spans = []
idx = 0
for w in words:
start = text.index(w, idx) # 中文需保证无重叠
end = start + len(w)
word_spans.append((w, start, end))
idx = end
# 2. 建立字符级到标签的映射
char_labels = ['O'] * len(text)
for s, e, L in sorted(offsets, key=lambda x: x[0]):
for i in range(s, e):
if i >= len(char_labels): break
if char_labels[i] != 'O':
continue # 简单策略:后者覆盖前者,可扩展为冲突报告
if s < len(char_labels):
char_labels[s] = f'B-{L}'
for i in range(s+1, e):
if i < len(char_labels):
char_labels[i] = f'I-{L}'
# 3. 词级聚合:取词内最长标签
iob_seq = []
for w, ws, we in word_spans:
sub = char_labels[ws:we]
if any(l.startswith('B-') or l.startswith('I-') for l in sub):
# 优先 B-
choice = next((l for l in sub if l.startswith('B-')), sub[0])
else:
choice = 'O'
# POS 用通用标记 'NN',可接第三方 POS 模型
iob_seq.append((w, 'NN', choice))
return iob_seq
def convert_file(jsonl_path, out_dir):
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
with open(jsonl_path, encoding='utf-8') as f, \
open(out_dir/'doccano.chunk', 'w', encoding='utf-8') as wf:
for line in f:
rec = json.loads(line)
text = rec['text']
labels = [(int(l[0]), int(l[1]), l[2]) for l in rec['label']]
iob = offsets_to_iob2(text, labels)
for w, pos, chunk in iob:
wf.write(f'{w} {pos} {chunk}\n')
wf.write('\n') # 空行分隔句子
# 执行转换
convert_file('doccano.jsonl', 'data/chunked')
# NLTK 端加载
from nltk.corpus.reader import ChunkedCorpusReader
reader = ChunkedCorpusReader('data/chunked', '.*chunk')
print(reader.chunked_words()[:5]) # 可直接喂给 NLTK 的 chunk 评估器
关键步骤回顾
- 分词对齐:中文必须用字符偏移反算到词,否则 IOB 序列错位
- 空行分隔:ChunkedCorpusReader 靠空行识别句子边界,不能省略
- 文件扩展名:
.chunk会被自动识别,若用.pos亦可,需保证三列
拓展思考
- 嵌套实体:Doccano 本身不支持嵌套,若业务需要,可改用分层 IOB2(LayeredChunkReader)或树括号嵌套;转换脚本需递归构建
nltk.Tree - 工业级 pipeline:把转换脚本封装成 Airflow Task,每日增量同步 Doccano PostgreSQL → IOB2 → NLTK 特征缓存 → 模型重训练,实现闭环迭代
- 性能优化:十亿字符级语料,可改用 Cython+memoryview 加速偏移对齐,或多进程分片写盘,保证转换速度 ≥ 200 MB/s
- 标签体系迁移:当 Doccano 标签与 OntoNotes 不一致时,用映射字典+正则归一化,并在 NLTK 端通过
chunk_types=参数限定评估范围,避免标签泄漏 - 端到端评估:用
nltk.chunk.util.accuracy对比人工 gold 与模型预测,把转换脚本与评估脚本一起纳入 GitLab CI,每次 MR 自动输出 F1,保证数据质量可回溯