Download code/2fca4cd-dirty-4e8c5dbd/src/textmatch.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 3.76 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/2fca4cd-dirty-4e8c5dbd/src/textmatch.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/2fca4cd-dirty-4e8c5dbd/src/textmatch.py
-
curl -L -o textmatch.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/2fca4cd-dirty-4e8c5dbd/src/textmatch.py
3.76 kB
| """ワードリスト照合の共通部品。正規化、語リストの読み込み、境界付きトライ正規表現。 | |
| ``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) + ")") | |