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
+10 -18
View File
@@ -10,17 +10,13 @@
"""
from __future__ import annotations
import ast
import re
import unicodedata
FW = {ord(c): ord(c) - 0xFEE0 for c in "0123456789+-×÷=()"}
FW[ord(" ")] = ord(" ")
_ALLOWED = (ast.Expression, ast.BinOp, ast.UnaryOp, ast.Constant, ast.Add, ast.Sub,
ast.Mult, ast.Div, ast.Pow, ast.Mod, ast.USub, ast.UAdd, ast.FloorDiv,
ast.Load)
from core.numeric import eval_exact, fmt_qty
from core.text import halfwidth, squeeze
# 学科自己的单位表留在本地:初中物理/化学的单位和小学不一样
_UNIT_ALIAS = {
"米": "m", "千米": "km", "厘米": "cm", "毫米": "mm",
"秒": "s", "分钟": "min", "小时": "h",
@@ -33,12 +29,12 @@ _UNITS = set(_UNIT_ALIAS.values()) | {"m/s", "km/h", "g/cm3", "kg/m3", "m2", "cm
def normalize(s: str) -> str:
"""初中版保留标点(语文默写要逐字比),只做全角转半角与去空白。"""
if s is None:
return ""
s = unicodedata.normalize("NFKC", str(s)).translate(FW)
s = s.replace("×", "*").replace("÷", "/").replace("=", "=")
s = halfwidth(str(s))
s = s.replace(",", ",").replace(";", ";").replace(":", ":")
return re.sub(r"\s+", "", s).strip()
return squeeze(s)
def strip_tail(s: str) -> str:
@@ -46,14 +42,10 @@ def strip_tail(s: str) -> str:
def safe_eval(expr: str):
"""只算四则运算;任何不认识的东西都抛 ValueError。"""
"""只算四则运算;任何不认识的东西都抛 ValueError(初中版约定:抛,不返回 None)。"""
if not expr or len(expr) > 80:
raise ValueError("bad")
tree = ast.parse(expr, mode="eval")
for node in ast.walk(tree):
if not isinstance(node, _ALLOWED):
raise ValueError("bad node")
return eval(compile(tree, "<judge>", "eval"), {"__builtins__": {}}, {})
return eval_exact(expr)
_CALC_OK = re.compile(r"^[0-9+\-*/().=]+$")
@@ -76,7 +68,7 @@ def judge_calc(user: str, answer: str):
if want is None:
return strip_tail(u) == strip_tail(a), ""
ok = abs(float(got) - float(want)) < 1e-6
return ok, "" if ok else f"你算的是 {got:g},正确答案是 {want:g}"
return ok, "" if ok else f"你算的是 {fmt_qty(got)},正确答案是 {fmt_qty(want)}"
def _split_value_unit(s: str):
@@ -102,7 +94,7 @@ def judge_numeric(user: str, answer: str):
if av is None:
return None, "参考答案没解析出来,这次不判"
ok = abs(uv - av) < 1e-6
return ok, "" if ok else f"你填 {uv:g}{uu or ''},正确答案是 {av:g}{au or ''}"
return ok, "" if ok else f"你填 {fmt_qty(uv)}{uu or ''},正确答案是 {fmt_qty(av)}{au or ''}"
def norm_formula(s: str) -> str: