File size: 3,760 Bytes
b5cbcc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""ワードリスト照合の共通部品。正規化、語リストの読み込み、境界付きトライ正規表現。

``filter_toxic.py`` と ``cooccurrence.py`` の両方から使うため、循環importを
避けて独立モジュールに置く。
"""

from __future__ import annotations

import re
import unicodedata
from pathlib import Path
from typing import Any


ASCII_EDGE = "[a-z0-9]"
KATAKANA_EDGE = "[ァ-ヶー]"


def normalize(value: Any) -> str:
    """ワードリストと本文を同じNFKC・小文字化規則で正規化する。"""

    if value is None:
        return ""
    return unicodedata.normalize("NFKC", str(value)).lower()


def read_terms(path: Path) -> list[str]:
    """1行1語のリストを読み、正規化する。空行と``#``始まりの行は無視する。"""

    if not path.exists():
        return []
    terms: list[str] = []
    for raw_line in path.read_text(encoding="utf-8").splitlines():
        term = normalize(raw_line.strip())
        if term and not term.startswith("#"):
            terms.append(term)
    return terms


def _edge_class(character: str) -> str | None:
    """語の端の文字種。ASCII英数字とカタカナだけを境界判定の対象にする。"""

    if re.fullmatch(ASCII_EDGE, character):
        return ASCII_EDGE
    if re.fullmatch(KATAKANA_EDGE, character):
        return KATAKANA_EDGE
    return None


def compile_trie_pattern(terms: list[str], boundaries: bool = True) -> re.Pattern[str]:
    """多数語を共通接頭辞付き正規表現へコンパイルする。

    ``boundaries`` が真のとき、語の端がASCII英数字なら英数字が隣接する位置、
    端がカタカナならカタカナ(長音を含む)が隣接する位置では一致させない。
    「メイク」中の「イク」、「DVD」中の「dv」のような単語内部の部分一致を
    防ぐ。漢字・ひらがなの端には境界を設けない。同じ位置では長い語を優先し、
    長い語が境界を満たさない場合だけ短い語で境界を確認する。
    """

    if not terms:
        return re.compile(r"(?!x)x")
    root: dict[str, Any] = {"terminal": False, "children": {}}
    for term in terms:
        node = root
        for character in term:
            node = node["children"].setdefault(character, {"terminal": False, "children": {}})
        node["terminal"] = True

    def lookahead(character: str) -> str:
        edge = _edge_class(character) if boundaries else None
        return f"(?!{edge})" if edge else ""

    def render(node: dict[str, Any], last_character: str) -> str:
        branches = [
            re.escape(character) + render(child, character)
            for character, child in sorted(node["children"].items())
        ]
        if not branches:
            body = ""
        elif len(branches) == 1:
            body = branches[0]
        else:
            body = "(?:" + "|".join(branches) + ")"
        if not node["terminal"]:
            return body
        end = lookahead(last_character)
        if not body:
            return end
        return "(?:" + body + "|" + end + ")"

    alternatives: list[str] = []
    for character, child in sorted(root["children"].items()):
        edge = _edge_class(character) if boundaries else None
        # 後読みは先頭文字を消費した後に置く。分岐が後読みで始まると
        # 正規表現エンジンの先頭文字による走査最適化が効かず、約4倍遅くなる。
        lookbehind = f"(?<!{edge}{re.escape(character)})" if edge else ""
        alternatives.append(re.escape(character) + lookbehind + render(child, character))
    return re.compile("(?:" + "|".join(alternatives) + ")")