Files
CaptchBreaker/inference/math_eval.py
2026-03-10 18:47:29 +08:00

67 lines
1.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
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.
"""
算式计算模块
解析并计算验证码中的算式表达式。
用正则提取数字和运算符,不使用 eval()。
支持: 加减乘除,个位到两位数运算。
"""
import re
# 匹配: 数字 运算符 数字 (后面可能跟 =? 等)
_EXPR_PATTERN = re.compile(
r"(\d+)\s*([+\-×÷xX*])\s*(\d+)"
)
# 运算符归一化映射
_OP_MAP = {
"+": "+",
"-": "-",
"×": "×",
"÷": "÷",
"x": "×",
"X": "×",
"*": "×",
}
def eval_captcha_math(expr: str) -> str:
"""
解析并计算验证码算式。
支持: 加减乘除,个位到两位数运算。
输入: "3+8=?""12×3=?""15-7=?""3+8"
输出: "11""36""8"
用正则提取数字和运算符,不使用 eval()。
Raises:
ValueError: 无法解析表达式
"""
match = _EXPR_PATTERN.search(expr)
if not match:
raise ValueError(f"无法解析算式: {expr!r}")
a = int(match.group(1))
op_raw = match.group(2)
b = int(match.group(3))
op = _OP_MAP.get(op_raw, op_raw)
if op == "+":
result = a + b
elif op == "-":
result = a - b
elif op == "×":
result = a * b
elif op == "÷":
if b == 0:
raise ValueError(f"除数为零: {expr!r}")
result = a // b
else:
raise ValueError(f"不支持的运算符: {op!r} 原式: {expr!r}")
return str(result)