Spaces:
Running
Running
Download vb_amount.py from jay0826/discord-bot: direct link, hf CLI and curl.
- Browser
- Download file 1.79 kB
-
https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_amount.py
- Command line
-
hf download hf://spaces/jay0826/discord-bot/vb_amount.py
-
curl -L -o vb_amount.py https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_amount.py
1.79 kB
| # -*- coding: utf-8 -*- | |
| """vb_amount — 金額文字解析(純函式,無外部依賴)。 | |
| 支援 1m / 500k / 2.5b 後綴與 + - * / ( ) 四則運算。 | |
| 用 ast 解析、白名單節點求值——絕不 eval(),免注入(安全鐵則)。 | |
| """ | |
| import ast as _ast | |
| import operator as _op | |
| import re | |
| from typing import Optional | |
| AMT_SUFFIX = {"k": 1_000, "m": 1_000_000, "b": 1_000_000_000} | |
| _AMT_OPS = {_ast.Add: _op.add, _ast.Sub: _op.sub, _ast.Mult: _op.mul, _ast.Div: _op.truediv, | |
| _ast.USub: _op.neg, _ast.UAdd: _op.pos} | |
| def _eval_amt(node): | |
| if isinstance(node, _ast.Expression): | |
| return _eval_amt(node.body) | |
| if isinstance(node, _ast.Constant) and isinstance(node.value, (int, float)): | |
| return float(node.value) | |
| if isinstance(node, _ast.BinOp) and type(node.op) in _AMT_OPS: | |
| return _AMT_OPS[type(node.op)](_eval_amt(node.left), _eval_amt(node.right)) | |
| if isinstance(node, _ast.UnaryOp) and type(node.op) in _AMT_OPS: | |
| return _AMT_OPS[type(node.op)](_eval_amt(node.operand)) | |
| raise ValueError("不支援的運算式") | |
| def parse_amount(s) -> Optional[float]: | |
| """把 '1m'/'500k'/'2.5b'/'100-20'/'(1m+500k)/2' 這類文字算成數字。 | |
| 不認得回 None;空字串/None 也回 None。""" | |
| if s is None: | |
| return None | |
| txt = str(s).strip().lower().replace(",", "").replace(",", "").replace(" ", "") | |
| if not txt: | |
| return None | |
| # 1m → (1*1000000);用括號保留運算優先級 | |
| txt = re.sub(r'(\d+(?:\.\d+)?)([kmb])', | |
| lambda m: f"({m.group(1)}*{AMT_SUFFIX[m.group(2)]})", txt) | |
| if not re.fullmatch(r'[\d\.\+\-\*\/\(\)]+', txt): | |
| return None | |
| try: | |
| return _eval_amt(_ast.parse(txt, mode="eval")) | |
| except Exception: | |
| return None | |