Files
cuotibiye/core/text.py
T

57 lines
1.9 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""文本归一化的小零件。
注意:两个产品的「归一化」策略不一样(小学版连标点一起去掉,初中版保留标点),
所以这里只提供零件,不提供一揽子 normalize——策略留在各自的包里。
"""
from __future__ import annotations
import re
import unicodedata
# 全角 → 半角:数字、加减乘除、等号、括号、句点、全角空格
FW = str.maketrans({
"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5",
"6": "6", "7": "7", "8": "8", "9": "9",
"+": "+", "-": "-", "×": "*", "÷": "/", "=": "=", "(": "(", ")": ")",
".": ".", " ": " ",
})
PUNCT = "。,、;:?!“”‘’()《》〈〉【】…—~·.,;:?!\"'()[]{}<>"
# 答案末尾常见单位(小学口径)
UNITS = ("平方厘米", "平方米", "立方厘米", "元", "角", "分", "厘米", "分米", "毫米",
"千米", "千克", "平方", "米", "克", "吨", "个", "只", "本", "支", "块",
"岁", "人", "天", "时", "秒", "度")
def halfwidth(s: str) -> str:
"""全角转半角(不删空格、不去标点)。"""
return unicodedata.normalize("NFKC", str(s or "")).translate(FW)
def squeeze(s: str) -> str:
"""去掉所有空白。"""
return re.sub(r"\s+", "", s or "")
def strip_punct(s: str) -> str:
return (s or "").strip(PUNCT)
def strip_units(s: str) -> str:
"""去掉答案末尾的单位(只去掉一个,避免把「平方米」拆两次)。"""
for u in UNITS:
if s.endswith(u):
return s[: -len(u)]
return s
def strip_tail(s: str) -> str:
"""去掉句末标点(初中版用:保留句中逗号冒号)。"""
return re.sub(r"[。.!!??;;]+$", "", s or "")
def has_chinese(s: str) -> bool:
return any("\u4e00" <= ch <= "\u9fff" for ch in (s or ""))