refactor: 抽出 core/(clock store text numeric),小学版与初中版共用归一化与数值解析
This commit is contained in:
+103
@@ -0,0 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数值解析:用 Fraction 精确算,避免 0.1 + 0.2 这种浮点噪声把「对的」判成「错的」。
|
||||
|
||||
两个产品都用它:
|
||||
- 小学版包一层 try/except 返回 None(拒答);
|
||||
- 初中版让异常往外抛(自己转成「不判」)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import re
|
||||
from fractions import Fraction
|
||||
|
||||
_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)
|
||||
|
||||
_MIXED = re.compile(r"^(-?\d+)(?:又| )(\d+)\s*/\s*(\d+)$")
|
||||
_FRAC = re.compile(r"^(-?\d+)\s*/\s*(\d+)$")
|
||||
_DEC = re.compile(r"^-?\d+(?:\.\d+)?$")
|
||||
|
||||
|
||||
def eval_exact(expr: str) -> Fraction:
|
||||
"""只允许数字与四则运算,返回精确分数。不认识的输入抛 ValueError。"""
|
||||
expr = re.sub(r"[^0-9+\-*/%().]", "", expr or "")
|
||||
if not expr or len(expr) > 64:
|
||||
raise ValueError("empty or too long")
|
||||
tree = ast.parse(expr, mode="eval")
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, _ALLOWED):
|
||||
raise ValueError(f"bad node {type(node).__name__}")
|
||||
if isinstance(node, ast.Constant) and (
|
||||
isinstance(node.value, bool) or not isinstance(node.value, (int, float))
|
||||
):
|
||||
raise ValueError("bad constant")
|
||||
value = _eval(tree.body)
|
||||
if value is None:
|
||||
raise ValueError("bad expression")
|
||||
return value
|
||||
|
||||
|
||||
def _eval(node) -> Fraction | None:
|
||||
if isinstance(node, ast.Expression):
|
||||
return _eval(node.body)
|
||||
if isinstance(node, ast.Constant):
|
||||
v = node.value
|
||||
return Fraction(str(v)) if isinstance(v, float) else Fraction(v)
|
||||
if isinstance(node, ast.UnaryOp):
|
||||
v = _eval(node.operand)
|
||||
return None if v is None else (-v if isinstance(node.op, ast.USub) else v)
|
||||
if isinstance(node, ast.BinOp):
|
||||
a, b = _eval(node.left), _eval(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
|
||||
|
||||
|
||||
def to_qty(text: str) -> Fraction | None:
|
||||
"""把「3/4」「1又1/2」「0.75」「-3/4」「2/8」读成一个精确数。"""
|
||||
from .text import halfwidth, squeeze
|
||||
|
||||
raw = re.sub(r"\s+", " ", halfwidth(text).strip())
|
||||
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 = squeeze(raw)
|
||||
m = _FRAC.match(s)
|
||||
if m:
|
||||
den = int(m.group(2))
|
||||
return None if den == 0 else Fraction(int(m.group(1)), den)
|
||||
if _DEC.match(s):
|
||||
return Fraction(s)
|
||||
return None
|
||||
|
||||
|
||||
def fmt_qty(x) -> str:
|
||||
"""3/10 而不是 0.3;整数不带小数点。"""
|
||||
if isinstance(x, Fraction):
|
||||
if x.denominator == 1:
|
||||
return str(x.numerator)
|
||||
return f"{x.numerator}/{x.denominator}"
|
||||
try:
|
||||
return str(int(x)) if abs(float(x) - round(float(x))) < 1e-9 else f"{float(x):g}"
|
||||
except (TypeError, ValueError):
|
||||
return str(x)
|
||||
Reference in New Issue
Block a user