蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行文本编码转码/清洗、中英文分词、纯 Python BPE 子词学习与 HMM-Viterbi 词性标注实验

PYTHONWindows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。explore-text-preprocessing.py
explore-text-preprocessing.py285 行
"""Independent offline NLP lab for Ch 04 (Text Preprocessing): encoding/cleaning, EN+ZH tokenization, BPE subwords, HMM-Viterbi POS."""
import json
import math
import platform
import re
from collections import Counter, defaultdict


def fmm_zh(text: str, vocab: set, max_len: int = 5):
    tokens, i, n = [], 0, len(text)
    while i < n:
        piece = text[i]
        for l in range(min(max_len, n - i), 0, -1):
            cand = text[i:i + l]
            if cand in vocab:
                piece = cand
                break
        tokens.append(piece)
        i += len(piece)
    return tokens


def train_bpe(word_freqs: dict, num_merges: int):
    vocab = {" ".join(list(w) + ["</w>"]): freq for w, freq in word_freqs.items()}
    merges = []
    for _ in range(num_merges):
        pairs = Counter()
        for word, freq in vocab.items():
            syms = word.split()
            for a, b in zip(syms, syms[1:]):
                pairs[(a, b)] += freq
        if not pairs:
            break
        best = max(pairs.items(), key=lambda kv: (kv[1], kv[0]))[0]
        merges.append(best)
        bigram = " ".join(best)
        replacement = "".join(best)
        new_vocab = {}
        for word, freq in vocab.items():
            new_vocab[word.replace(bigram, replacement)] = freq
        vocab = new_vocab
    return merges, vocab


def apply_bpe(word: str, merges: list):
    syms = list(word) + ["</w>"]
    for a, b in merges:
        i = 0
        out = []
        while i < len(syms):
            if i + 1 < len(syms) and syms[i] == a and syms[i + 1] == b:
                out.append(a + b)
                i += 2
            else:
                out.append(syms[i])
                i += 1
        syms = out
    return syms


def run_cases():
    cases = []

    # 1. Encoding conversion (GBK -> UTF-8, invalid bytes) + HTML/emoji/control/date/number cleaning
    sample_zh = "示例文本"
    gbk_bytes = sample_zh.encode("gbk")
    utf8_bytes = gbk_bytes.decode("gbk").encode("utf-8")
    roundtrip_ok = utf8_bytes.decode("utf-8") == sample_zh and len(gbk_bytes) == 8 and len(utf8_bytes) == 12
    corrupt_decoded = b"abc\xff\xfe123".decode("utf-8", errors="replace")

    html_raw = "<p>这是一段<b>HTML</b>文本</p>"
    html_clean = re.sub(r"<[^>]+>", "", html_raw)
    noisy = "Hello\x00\x07!😀 价格1000元,日期01/01/2023。"
    no_ctrl = re.sub(r"[\x00-\x1f\x7f]", "", noisy)
    no_emoji = re.sub(r"[\U00010000-\U0010ffff]", "", no_ctrl)
    norm_punct = no_emoji.replace("!", "!").replace(",", ",").replace("。", ".")
    norm_date = re.sub(r"(\d{2})/(\d{2})/(\d{4})", r"\3-\1-\2", norm_punct)
    norm_num = re.sub(r"(?<!\d)(\d{4})(?!\d|-)", lambda m: f"{int(m.group(1)):,}", norm_date)

    c1_ok = (
        roundtrip_ok
        and "\ufffd" in corrupt_decoded
        and html_clean == "这是一段HTML文本"
        and "😀" not in norm_num
        and "\x00" not in norm_num
        and "1,000" in norm_num
        and "2023-01-01" in norm_num
    )
    cases.append(dict(
        name="encoding_and_text_cleaning",
        inputs=dict(sample_zh=sample_zh, html_raw=html_raw),
        prerequisites="准备 GBK 编码字节、非法 UTF-8 字节、HTML 标签、表情符号、控制字符与非标准日期数字文本。",
        action="执行 GBK→UTF-8 往返转码、容错解码、正则去标签/控制符/表情,并标准化标点、数字和日期。",
        expected=dict(gbk_8_utf8_12_roundtrip=True, corrupt_replaced=True, html_stripped=True, special_and_date_normalized=True),
        actual=dict(
            gbk_8_utf8_12_roundtrip=roundtrip_ok,
            corrupt_replaced=("\ufffd" in corrupt_decoded),
            html_stripped=(html_clean == "这是一段HTML文本"),
            special_and_date_normalized=("😀" not in norm_num and "\x00" not in norm_num and "1,000" in norm_num and "2023-01-01" in norm_num),
        ),
        measurements=dict(
            gbk_byte_len=len(gbk_bytes),
            utf8_byte_len=len(utf8_bytes),
            html_clean=html_clean,
            normalized_text=norm_num,
        ),
        passed=c1_ok,
    ))

    # 2. English tokenization (contractions, hyphens, punctuation) & Chinese FMM dictionary tokenization
    en_text = "I'm studying state-of-the-art Natural Language Processing!"
    en_tokens = re.findall(r"[A-Za-z]+(?:-[A-Za-z]+)+|'[A-Za-z]+|[A-Za-z]+|[^\w\s]", en_text)
    en_simple = re.findall(r"[A-Za-z]+|[^\w\s]", "Natural Language Processing is fascinating!")

    zh_vocab = {"自然语言", "处理", "非常", "有趣", "分词", "技术"}
    zh_tokens = fmm_zh("自然语言处理非常有趣", zh_vocab)

    c2_ok = (
        en_simple == ["Natural", "Language", "Processing", "is", "fascinating", "!"]
        and en_tokens == ["I", "'m", "studying", "state-of-the-art", "Natural", "Language", "Processing", "!"]
        and zh_tokens == ["自然语言", "处理", "非常", "有趣"]
    )
    cases.append(dict(
        name="english_and_chinese_tokenization",
        inputs=dict(en_text=en_text, zh_text="自然语言处理非常有趣"),
        prerequisites="构建处理英文缩写/连字符/标点的正则规则分词器,以及含领域词表的中文正向最大匹配分词器。",
        action="对英文基础句、含缩写与连字符句以及中文句分别分词,校验切分单元。",
        expected=dict(en_basic_exact=True, en_contraction_hyphen_exact=True, zh_fmm_exact=True),
        actual=dict(
            en_basic_exact=(en_simple == ["Natural", "Language", "Processing", "is", "fascinating", "!"]),
            en_contraction_hyphen_exact=(en_tokens == ["I", "'m", "studying", "state-of-the-art", "Natural", "Language", "Processing", "!"]),
            zh_fmm_exact=(zh_tokens == ["自然语言", "处理", "非常", "有趣"]),
        ),
        measurements=dict(en_simple=en_simple, en_tokens=en_tokens, zh_tokens=zh_tokens),
        passed=c2_ok,
    ))

    # 3. Byte Pair Encoding (BPE) subword learning + BERT-Chinese CJK character splitting
    word_freqs = {"low": 5, "lowest": 2, "newer": 6, "wider": 3, "new": 2}
    merges, _ = train_bpe(word_freqs, num_merges=8)
    oov_subwords = apply_bpe("lowest", merges)
    unseen_subwords = apply_bpe("newest", merges)
    bert_zh_chars = [ch for ch in "自然语言处理"]

    learned_er = any("".join(m).startswith("er") for m in merges)
    c3_ok = (
        len(merges) == 8
        and learned_er
        and "new" in unseen_subwords
        and bert_zh_chars == ["自", "然", "语", "言", "处", "理"]
    )
    cases.append(dict(
        name="bpe_subword_tokenization",
        inputs=dict(corpus_words=word_freqs, num_merges=8, zh_bert_sample="自然语言处理"),
        prerequisites="基于频次词表从零执行 8 轮 BPE 相邻字符对合并,并模拟 BERT 中文单字切分。",
        action="核对学到的高频子词合并对、未登录词 newest 的子词拆分,以及中文单字列表。",
        expected=dict(merges_8=True, learned_er_suffix=True, unseen_contains_new=True, bert_zh_6_chars=True),
        actual=dict(
            merges_8=(len(merges) == 8),
            learned_er_suffix=learned_er,
            unseen_contains_new=("new" in unseen_subwords),
            bert_zh_6_chars=(bert_zh_chars == ["自", "然", "语", "言", "处", "理"]),
        ),
        measurements=dict(
            merges=["".join(m) for m in merges],
            lowest_subwords=oov_subwords,
            newest_subwords=unseen_subwords,
            bert_zh_chars=bert_zh_chars,
        ),
        passed=c3_ok,
    ))

    # 4. HMM + Viterbi POS tagging (Penn Treebank subset + OOV handling & accuracy/confusion metrics)
    train_sents = [
        [("they", "PRP"), ("run", "VB"), ("fast", "RB")],
        [("she", "PRP"), ("read", "VB"), ("good", "JJ"), ("book", "NN")],
        [("he", "PRP"), ("wrote", "VB"), ("clean", "JJ"), ("code", "NN")],
        [("we", "PRP"), ("build", "VB"), ("great", "JJ"), ("system", "NN")],
        [("they", "PRP"), ("speak", "VB"), ("clearly", "RB")],
        [("she", "PRP"), ("likes", "VB"), ("new", "JJ"), ("model", "NN")],
        [("he", "PRP"), ("trains", "VB"), ("deep", "JJ"), ("network", "NN")],
        [("we", "PRP"), ("test", "VB"), ("fast", "JJ"), ("parser", "NN")],
    ]
    trans_counts = defaultdict(Counter)
    emit_counts = defaultdict(Counter)
    tag_counts = Counter()
    seen_words = set()
    for sent in train_sents:
        prev = "<START>"
        for word, tag in sent:
            trans_counts[prev][tag] += 1
            emit_counts[tag][word] += 1
            tag_counts[tag] += 1
            seen_words.add(word)
            prev = tag
    tags = sorted(tag_counts.keys())
    vocab_size = len(seen_words) + 1

    def viterbi_pos(words):
        dp = []
        back = []
        for idx, w in enumerate(words):
            cur = {}
            bp = {}
            for t in tags:
                # Suffix hint for OOV words (e.g. -ly -> RB, -ing -> VB)
                emit_p = (emit_counts[t][w] + 0.5) / (tag_counts[t] + 0.5 * vocab_size)
                if w not in seen_words:
                    if w.endswith("ly") and t == "RB":
                        emit_p *= 5.0
                    elif w.endswith("ing") and t == "VB":
                        emit_p *= 3.0
                    elif t == "NN":
                        emit_p *= 1.5
                if idx == 0:
                    tr_p = (trans_counts["<START>"][t] + 0.5) / (len(train_sents) + 0.5 * len(tags))
                    cur[t] = math.log(tr_p) + math.log(emit_p)
                    bp[t] = "<START>"
                else:
                    best_score, best_prev = -1e18, tags[0]
                    for pt in tags:
                        tr_p = (trans_counts[pt][t] + 0.5) / (tag_counts[pt] + 0.5 * len(tags))
                        sc = dp[-1][pt] + math.log(tr_p) + math.log(emit_p)
                        if sc > best_score:
                            best_score, best_prev = sc, pt
                    cur[t] = best_score
                    bp[t] = best_prev
            dp.append(cur)
            back.append(bp)
        best_last = max(tags, key=lambda t: dp[-1][t])
        seq = [best_last]
        for i in range(len(words) - 1, 0, -1):
            seq.append(back[i][seq[-1]])
        return list(reversed(seq))

    test_sents = [
        [("they", "PRP"), ("build", "VB"), ("clean", "JJ"), ("pipeline", "NN")],  # 'pipeline' is OOV
        [("she", "PRP"), ("spoke", "VB"), ("quickly", "RB")],  # 'spoke', 'quickly' are OOV
    ]
    total_tok = correct_tok = oov_tok = oov_correct = 0
    predictions = []
    for sent in test_sents:
        words = [w for w, _ in sent]
        gold = [t for _, t in sent]
        pred = viterbi_pos(words)
        predictions.append(list(zip(words, pred)))
        for w, g, p in zip(words, gold, pred):
            total_tok += 1
            if g == p:
                correct_tok += 1
            if w not in seen_words:
                oov_tok += 1
                if g == p:
                    oov_correct += 1
    acc = correct_tok / total_tok
    oov_acc = oov_correct / oov_tok
    # Also verify ICTCLAS 5-tag mapping structure
    ictclas_sample = [("自然语言", "n"), ("处理", "v"), ("非常", "d"), ("有趣", "a"), ("它", "r")]
    c4_ok = acc == 1.0 and oov_acc == 1.0 and len(ictclas_sample) == 5
    cases.append(dict(
        name="hmm_viterbi_pos_tagging",
        inputs=dict(train_sentences=len(train_sents), test_tokens=total_tok, oov_tokens=oov_tok),
        prerequisites="在 Penn Treebank 5 类核心词性(NN/VB/JJ/RB/PRP)上训练 HMM 并以 Viterbi 解码,含 3 个未登录词。",
        action="在留出测试句上评估总体词性标注准确率与 OOV 准确率,并核对 ICTCLAS 中文词性标签集对应关系。",
        expected=dict(overall_acc_1=True, oov_acc_1=True, ictclas_5_tags=True),
        actual=dict(
            overall_acc_1=(acc == 1.0),
            oov_acc_1=(oov_acc == 1.0),
            ictclas_5_tags=(len(ictclas_sample) == 5),
        ),
        measurements=dict(
            overall_accuracy=round(acc, 4),
            oov_accuracy=round(oov_acc, 4),
            predictions=predictions,
            ictclas_tags=[tag for _, tag in ictclas_sample],
        ),
        passed=c4_ok,
    ))

    print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), ensure_ascii=False))


if __name__ == "__main__":
    run_cases()
本例需在 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。

入口文件:projects/nlp-text-preprocessing-lab/explore-text-preprocessing.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-text-preprocessing.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联21章) · 含当前章节或实例 · mbskycom202612a545.zip

下载课程关联工程包:自然语言处理 NLP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a561.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习