refactor: 抽出 core/(clock store text numeric),小学版与初中版共用归一化与数值解析

This commit is contained in:
2026-11-19 08:58:57 +08:00
parent f85adf2af0
commit 5e9ca5589a
10 changed files with 312 additions and 164 deletions
+15 -112
View File
@@ -5,107 +5,41 @@
B 类(应用题)只判最终结果;C 类不判,调用方应传 judge_type='manual'。
原则:宁可不判,不可判错——算不出来就返回 None(拒答),交给人工。
数值与字符串的底层解析在 core/(初中版共用同一套)。
"""
from __future__ import annotations
import ast
import re
import unicodedata
from fractions import Fraction
FW = str.maketrans({
"0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5",
"6": "6", "7": "7", "8": "8", "9": "9",
"+": "+", "-": "-", "×": "*", "÷": "/", "=": "=", "(": "(", ")": ")",
".": ".", " ": " ",
})
PUNCT = "。,、;:?!“”‘’()《》〈〉【】…—~·.,;:?!\"'()[]{}<>"
from core.numeric import eval_exact, fmt_qty
from core.numeric import to_qty as _core_to_qty
from core.text import FW, PUNCT, halfwidth, squeeze, strip_punct, strip_units
def normalize(text: str | None) -> str:
if text is None:
return ""
s = unicodedata.normalize("NFKC", str(text)).translate(FW)
s = s.strip()
s = re.sub(r"\s+", "", s)
return s.strip(PUNCT)
return strip_punct(squeeze(halfwidth(text)))
def normalize_answer(text: str | None) -> str:
"""去掉末尾的「=」与单位、括号,用于比较。"""
s = normalize(text)
s = s.rstrip("=")
s = re.sub(r"(元|角|分|米|厘米|分米|毫米|千米|克|千克|吨|个|只|本|支|块|岁|人|天|时|分|秒|度|平方厘米|平方米|立方厘米)$", "", s)
return s
s = normalize(text).rstrip("=")
return strip_units(s)
_ALLOWED = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant,
ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Mod, ast.USub, ast.UAdd, ast.Pow)
def safe_eval(expr: str) -> float | None:
"""只允许数字与四则运算,其余一律拒答。"""
expr = normalize(expr).replace("=", "")
expr = re.sub(r"[^0-9+\-*/%().]", "", expr)
if not expr or len(expr) > 64:
return None
def safe_eval(expr: str):
"""只允许数字与四则运算;算不出来返回 None(拒答)。"""
try:
tree = ast.parse(expr, mode="eval")
except SyntaxError:
return None
for node in ast.walk(tree):
if not isinstance(node, _ALLOWED):
return None
if isinstance(node, ast.Constant) and not isinstance(node.value, (int, float)):
return None
try:
value = _eval_fraction(tree.body)
return eval_exact(normalize(expr).replace("=", ""))
except Exception:
return None
if value is None:
return None
return value
def _eval_fraction(node):
"""用 Fraction 求值:3/4*2/5 要得 3/10,不能变成 0.30000000000000004。"""
if isinstance(node, ast.Expression):
return _eval_fraction(node.body)
if isinstance(node, ast.Constant):
v = node.value
if isinstance(v, bool) or not isinstance(v, (int, float)):
return None
return Fraction(str(v)) if isinstance(v, float) else Fraction(v)
if isinstance(node, ast.UnaryOp):
v = _eval_fraction(node.operand)
if v is None:
return None
return -v if isinstance(node.op, ast.USub) else v
if isinstance(node, ast.BinOp):
a = _eval_fraction(node.left)
b = _eval_fraction(node.right)
if a is None or b is None:
return None
if isinstance(node.op, ast.Add):
return a + b
if isinstance(node.op, ast.Sub):
return a - b
if isinstance(node.op, ast.Mult):
return a * b
if isinstance(node.op, ast.Div):
return None if b == 0 else a / b
if isinstance(node.op, ast.Mod):
return None if b == 0 else a % b
if isinstance(node.op, ast.Pow):
if b.denominator != 1 or abs(b) > 8:
return None
return a ** int(b)
return None
return None
_MIXED = re.compile(r"^(-?\d+)(?:又|\s)(\d+)\s*/\s*(\d+)$")
_FRAC = re.compile(r"^(-?\d+)\s*/\s*(\d+)$")
def to_qty(text: str | None):
"""支持「3/4」「1又1/2」「0.75」「-3/4」「2/8」这几种写法。"""
return _core_to_qty(text or "")
def _num(text: str | None):
@@ -119,35 +53,9 @@ def _num(text: str | None):
return safe_eval(s)
def to_qty(text: str | None):
"""支持 3/4、1又1/2、0.75、-3/4、2/8 这几种写法。"""
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW).strip()
raw = re.sub(r"\s+", " ", raw)
m = _MIXED.match(raw)
if m:
whole, num, den = int(m.group(1)), int(m.group(2)), int(m.group(3))
if den == 0:
return None
sign = -1 if whole < 0 else 1
return sign * (abs(whole) + Fraction(num, den))
s = normalize(text)
if not s:
return None
m = _FRAC.match(s)
if m:
den = int(m.group(2))
if den == 0:
return None
return Fraction(int(m.group(1)), den)
if re.fullmatch(r"-?\d+(?:\.\d+)?", s):
return Fraction(s)
return None
def _dirty(text: str | None) -> bool:
"""算式里混进了非数字字符(认不出的笔画、字母、问号)→ 不判。"""
raw = unicodedata.normalize("NFKC", str(text or "")).translate(FW)
raw = raw.replace("又", "")
raw = halfwidth(text).replace("又", "")
return bool(re.search(r"[^0-9+\-*/%().=\s]", raw))
@@ -166,12 +74,7 @@ def judge_calc(expected: str | None, given: str | None, tol: float = 1e-6):
return ok, "数值一致" if ok else f"应为 {_fmt(e)},你写的是 {_fmt(g)}"
def _fmt(x) -> str:
if isinstance(x, Fraction):
if x.denominator == 1:
return str(x.numerator)
return f"{x.numerator}/{x.denominator}"
return str(int(x)) if abs(x - round(x)) < 1e-9 else f"{x:g}"
_fmt = fmt_qty
def judge_text(expected: str | None, given: str | None):