跳到主要内容

人民币金额大写

收藏0

金额小写与中文大写互转、大写一致性校验、批量处理,适用于报销、合同、支票

让 AI 安装

MercuryLV2最新版本 0.1.0更新于 2026-12-01下载 0 次

scripts/rmb_amount.py

14.9 KB
1#!/usr/bin/env python3
2"""Convert RMB amounts between plain decimals and Chinese financial
3uppercase (人民币大写), and verify whether a given uppercase string matches
4the amount.
5
6Rules follow the common Chinese financial writing convention:
7 零壹贰叁肆伍陆柒捌玖 + 分角元拾佰仟万亿
8No network access, no third-party dependencies, Decimal arithmetic.
9"""
10
11import argparse
12import json
13import re
14import sys
15from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
16
17DIGITS = "零壹贰叁肆伍陆柒捌玖"
18DIGIT_MAP = {ch: i for i, ch in enumerate(DIGITS)}
19GROUP_UNITS = ["", "万", "亿", "万亿"]
20SMALL_UNITS = [(1000, "仟"), (100, "佰"), (10, "拾"), (1, "")]
21PREFIX = "人民币"
22MAX_INT = 10 ** 16 - 1 # 9999 万亿
23CENT = Decimal("0.01")
24
25
26class AmountError(Exception):
27 """Input that should exit with code 2."""
28
29
30def normalize_amount(text):
31 """Parse a plain amount string into an exact Decimal with 2 decimals."""
32 if text is None:
33 raise AmountError("金额为空")
34 raw = str(text).strip()
35 if not raw:
36 raise AmountError("金额为空")
37
38 s = raw.replace(" ", "").replace("\u3000", "")
39 for mark in ("¥", "¥", ",", ",", "_"):
40 s = s.replace(mark, "")
41
42 if s.startswith(PREFIX):
43 s = s[len(PREFIX):]
44 if s.endswith("元"):
45 s = s[:-1]
46 if s in ("", "-", "+"):
47 raise AmountError("金额「%s」里没有数字" % raw)
48
49 if s.startswith("负"):
50 s = "-" + s[1:]
51
52 try:
53 value = Decimal(s)
54 except InvalidOperation:
55 raise AmountError("「%s」不是有效金额,只支持数字、正负号和小数点" % raw)
56
57 if value.is_nan() or value.is_infinite():
58 raise AmountError("「%s」不是有效金额" % raw)
59
60 warnings = []
61 if -value.as_tuple().exponent > 2:
62 warnings.append("原金额超过两位小数,已按四舍五入保留到分")
63
64 rounded = value.quantize(CENT, rounding=ROUND_HALF_UP)
65 if rounded == 0:
66 rounded = Decimal("0.00")
67 if abs(rounded) > Decimal("9999999999999999.99"):
68 raise AmountError("金额超出支持范围(最多 9999 万亿元)")
69 if rounded != value and not warnings:
70 warnings.append("金额已按四舍五入保留到分")
71
72 return rounded, warnings
73
74
75def four_digits(n):
76 """Render 1-9999 with 仟佰拾 and internal zero collapsing."""
77 out = ""
78 pending_zero = False
79 for div, unit in SMALL_UNITS:
80 d = (n // div) % 10
81 if d == 0:
82 if out:
83 pending_zero = True
84 continue
85 if pending_zero:
86 out += "零"
87 pending_zero = False
88 out += DIGITS[d] + unit
89 return out
90
91
92def integer_to_upper(n):
93 if n == 0:
94 return ""
95 groups = []
96 while n > 0:
97 groups.append(n % 10000)
98 n //= 10000
99 if len(groups) > len(GROUP_UNITS):
100 raise AmountError("金额超出支持范围(最多 9999 万亿元)")
101
102 out = ""
103 need_zero = False
104 for idx in range(len(groups) - 1, -1, -1):
105 g = groups[idx]
106 if g == 0:
107 if out:
108 need_zero = True
109 continue
110 chunk = four_digits(g)
111 if out and (need_zero or g < 1000):
112 out += "零"
113 out += chunk + GROUP_UNITS[idx]
114 need_zero = False
115 return out
116
117
118def upper_from_decimal(value, prefix=True):
119 """Render an amount as Chinese financial uppercase."""
120 negative = value < 0
121 absv = -value if negative else value
122 cents = int(absv.quantize(CENT, rounding=ROUND_HALF_UP) * 100)
123 yuan = cents // 100
124 jiao = (cents // 10) % 10
125 fen = cents % 10
126
127 if yuan > MAX_INT:
128 raise AmountError("金额超出支持范围(最多 9999 万亿元)")
129
130 body = integer_to_upper(yuan)
131
132 if yuan == 0 and jiao == 0 and fen == 0:
133 body = "零元整"
134 elif yuan == 0:
135 if jiao > 0 and fen > 0:
136 body = DIGITS[jiao] + "角" + DIGITS[fen] + "分"
137 elif jiao > 0:
138 body = DIGITS[jiao] + "角整"
139 else:
140 body = DIGITS[fen] + "分"
141 else:
142 body += "元"
143 if jiao > 0 and fen > 0:
144 body += DIGITS[jiao] + "角" + DIGITS[fen] + "分"
145 elif jiao > 0:
146 body += DIGITS[jiao] + "角整"
147 elif fen > 0:
148 body += "零" + DIGITS[fen] + "分"
149 else:
150 body += "整"
151
152 if negative:
153 body = "负" + body
154 if prefix:
155 body = PREFIX + body
156 return body
157
158
159def _parse_integer_part(text):
160 total = 0
161 section = 0
162 number = None
163 i = 0
164 n = len(text)
165 while i < n:
166 ch = text[i]
167 if ch in DIGIT_MAP:
168 number = DIGIT_MAP[ch]
169 elif ch == "零":
170 pass
171 elif ch in ("拾", "佰", "仟"):
172 mult = {"拾": 10, "佰": 100, "仟": 1000}[ch]
173 section += (number if number is not None else 1) * mult
174 number = None
175 elif ch in ("万", "亿"):
176 group = 10 ** 4
177 if ch == "亿":
178 group = 10 ** 8
179 elif i + 1 < n and text[i + 1] == "亿":
180 i += 1
181 group = 10 ** 12
182 section += number if number is not None else 0
183 number = None
184 total += section * group
185 section = 0
186 else:
187 raise AmountError("大写金额里有不认识的字符「%s」" % ch)
188 i += 1
189 total += section + (number if number is not None else 0)
190 return total
191
192
193def parse_upper(text, prefix=True):
194 """Parse a Chinese uppercase amount back into a Decimal."""
195 if text is None:
196 raise AmountError("大写金额为空")
197 raw = str(text).strip()
198 if not raw:
199 raise AmountError("大写金额为空")
200
201 s = raw.replace(" ", "").replace("\u3000", "")
202 if s.startswith(PREFIX):
203 s = s[len(PREFIX):]
204 negative = False
205 if s.startswith("负") or s.startswith("-"):
206 negative = True
207 s = s[1:]
208 if s.startswith(PREFIX):
209 s = s[len(PREFIX):]
210 if not s:
211 raise AmountError("大写金额为空")
212
213 compare_text = s[:-1] + "整" if s.endswith("正") else s
214 work = s[:-1] if s.endswith(("整", "正")) else s
215 if not work:
216 raise AmountError("大写金额为空")
217
218 yuan_part = work
219 frac_part = ""
220 idx = -1
221 for mark in ("元", "圆"):
222 pos = work.find(mark)
223 if pos >= 0:
224 idx = pos
225 break
226 if idx >= 0:
227 yuan_part = work[:idx]
228 frac_part = work[idx + 1:]
229 elif "角" in work or "分" in work:
230 yuan_part = ""
231 frac_part = work
232
233 yuan = _parse_integer_part(yuan_part) if yuan_part else 0
234 if yuan > MAX_INT:
235 raise AmountError("大写金额超出支持范围(最多 9999 万亿元)")
236
237 jiao = 0
238 fen = 0
239 last = None
240 for ch in frac_part:
241 if ch in DIGIT_MAP:
242 last = DIGIT_MAP[ch]
243 elif ch == "零":
244 last = None
245 elif ch == "角":
246 jiao = last if last is not None else 0
247 last = None
248 elif ch == "分":
249 fen = last if last is not None else 0
250 last = None
251 else:
252 raise AmountError("大写金额里有不认识的字符「%s」" % ch)
253 if last is not None:
254 raise AmountError("大写金额末尾的「%s」后面缺角或分" % DIGITS[last])
255
256 value = Decimal(yuan) + Decimal(jiao) / 10 + Decimal(fen) / 100
257 if negative:
258 value = -value
259
260 canonical = upper_from_decimal(value, prefix=prefix)
261 warnings = []
262 sign_text = ("负" if negative else "") + compare_text
263 compare_target = (PREFIX + sign_text) if prefix else sign_text
264 if canonical != compare_target:
265 warnings.append("写法不是规范大写,规范写法为「%s」" % canonical)
266
267 return value.quantize(CENT), canonical, warnings
268
269
270def strip_prefix(text):
271 s = str(text).strip().replace(" ", "").replace("\u3000", "")
272 if s.startswith(PREFIX):
273 s = s[len(PREFIX):]
274 return s
275
276
277def do_upper(args):
278 value, warn = normalize_amount(args.amount)
279 text = upper_from_decimal(value, prefix=not args.no_prefix)
280 if args.json:
281 return 0, {
282 "action": "upper",
283 "input": str(args.amount),
284 "amount": str(value),
285 "upper": text,
286 "negative": value < 0,
287 "warnings": warn,
288 }
289 lines = [
290 "输入:%s" % str(args.amount),
291 "金额:%s" % value,
292 "大写:%s" % text,
293 ]
294 if warn:
295 lines.append("提示:" + ";".join(warn))
296 return 0, "\n".join(lines)
297
298
299def do_lower(args):
300 value, canonical, warn = parse_upper(args.upper, prefix=not args.no_prefix)
301 if args.json:
302 return 0, {
303 "action": "lower",
304 "input": str(args.upper),
305 "amount": str(value),
306 "canonical": canonical,
307 "warnings": warn,
308 }
309 lines = [
310 "输入:%s" % str(args.upper),
311 "金额:%s" % value,
312 "规范写法:%s" % canonical,
313 ]
314 if warn:
315 lines.append("提示:" + ";".join(warn))
316 return 0, "\n".join(lines)
317
318
319def do_check(args):
320 value, warn = normalize_amount(args.amount)
321 canonical = upper_from_decimal(value, prefix=not args.no_prefix)
322 given_norm = str(args.upper).strip().replace(" ", "").replace("\u3000", "")
323 ok = given_norm in (canonical, strip_prefix(canonical))
324 extra = []
325 if not ok:
326 extra.append("不一致:金额 %s 的规范大写是「%s」" % (value, canonical))
327 warnings = warn + extra
328
329 if args.json:
330 return (0 if ok else 2), {
331 "action": "check",
332 "amount": str(value),
333 "given": str(args.upper),
334 "canonical": canonical,
335 "ok": ok,
336 "warnings": warnings,
337 }
338
339 lines = [
340 "金额:%s" % value,
341 "待校验:%s" % str(args.upper),
342 "规范写法:%s" % canonical,
343 "结论:%s" % ("一致" if ok else "不一致"),
344 ]
345 if warnings:
346 lines.append("提示:" + ";".join(warnings))
347 return (0 if ok else 2), "\n".join(lines)
348
349
350BATCH_SEP = re.compile(r"\s*(?:=>|->)\s*")
351
352
353def do_batch(args):
354 lines = []
355 if args.file:
356 try:
357 with open(args.file, "r", encoding="utf-8-sig") as fh:
358 lines.extend(fh.read().splitlines())
359 except OSError as exc:
360 raise AmountError("读不了文件:%s" % exc)
361 if args.line:
362 lines.extend(args.line)
363 if not lines:
364 raise AmountError("没有要处理的内容,用 --file 或 --line 给出")
365
366 ok_items = []
367 errors = []
368 total = 0
369 mismatches = 0
370
371 for idx, line in enumerate(lines, start=1):
372 s = line.strip()
373 if not s or s.startswith("#"):
374 continue
375 total += 1
376 parts = BATCH_SEP.split(s, maxsplit=1)
377 amount_text = parts[0].strip()
378 given = parts[1].strip() if len(parts) == 2 else None
379 try:
380 value, warn = normalize_amount(amount_text)
381 canonical = upper_from_decimal(value, prefix=not args.no_prefix)
382 except AmountError as exc:
383 errors.append({"index": idx, "line": s, "error": str(exc)})
384 continue
385
386 item = {
387 "index": idx,
388 "amount": str(value),
389 "upper": canonical,
390 "warnings": warn,
391 }
392 if given is not None:
393 ok = given.replace(" ", "") in (canonical, strip_prefix(canonical))
394 item["given"] = given
395 item["ok"] = ok
396 if not ok:
397 mismatches += 1
398 item["warnings"] = warn + ["与规范写法不一致"]
399 ok_items.append(item)
400
401 code = 0 if (not errors and not mismatches) else 2
402
403 if args.json:
404 return code, {
405 "action": "batch",
406 "total": total,
407 "ok": len(ok_items),
408 "mismatch": mismatches,
409 "failed": len(errors),
410 "items": ok_items,
411 "errors": errors,
412 }
413
414 out = []
415 for item in ok_items:
416 if "given" in item:
417 out.append("%s 元 -> %s(%s)" % (
418 item["amount"], item["upper"], "一致" if item["ok"] else "不一致"))
419 else:
420 out.append("%s 元 -> %s" % (item["amount"], item["upper"]))
421 if errors:
422 out.append("")
423 out.append("未处理的行:")
424 for e in errors:
425 out.append(" 第 %d 行 %s:%s" % (e["index"], e["line"], e["error"]))
426 out.append("")
427 out.append("合计 %d 行,处理 %d,不一致 %d,失败 %d" % (
428 total, len(ok_items), mismatches, len(errors)))
429 return code, "\n".join(out)
430
431
432def write_out(path, text):
433 with open(path, "w", encoding="utf-8", newline="\n") as fh:
434 fh.write(text if text.endswith("\n") else text + "\n")
435
436
437def build_parser():
438 p = argparse.ArgumentParser(
439 prog="rmb_amount.py",
440 description="人民币金额大小写转换与校验:小写转大写、大写转小写、一致性校验、批量处理。",
441 )
442 sub = p.add_subparsers(dest="action", required=True)
443
444 def common(sp):
445 sp.add_argument("--json", action="store_true", help="输出 JSON")
446 sp.add_argument("--out", help="把结果写入文件(UTF-8)")
447 sp.add_argument("--no-prefix", action="store_true", help="不加「人民币」前缀")
448
449 up = sub.add_parser("upper", help="小写金额转中文大写")
450 up.add_argument("--amount", required=True, help="金额,例如 1234.56 或 ¥1,234.56")
451 common(up)
452
453 lo = sub.add_parser("lower", help="中文大写转小写金额")
454 lo.add_argument("--upper", required=True, help="大写金额,例如 壹仟贰佰叁拾肆元伍角陆分")
455 common(lo)
456
457 ck = sub.add_parser("check", help="校验大写是否与金额一致")
458 ck.add_argument("--amount", required=True, help="金额")
459 ck.add_argument("--upper", required=True, help="待校验的大写")
460 common(ck)
461
462 bt = sub.add_parser("batch", help="批量转换,每行一个金额,或「金额 => 大写」做校验")
463 bt.add_argument("--file", help="从文件读取(UTF-8)")
464 bt.add_argument("--line", action="append", help="直接给一行,可重复")
465 common(bt)
466
467 return p
468
469
470def main(argv=None):
471 parser = build_parser()
472 args = parser.parse_args(argv)
473
474 try:
475 if args.action == "upper":
476 code, payload = do_upper(args)
477 elif args.action == "lower":
478 code, payload = do_lower(args)
479 elif args.action == "check":
480 code, payload = do_check(args)
481 else:
482 code, payload = do_batch(args)
483 except AmountError as exc:
484 sys.stderr.write("错误:%s\n" % exc)
485 return 2
486
487 text = json.dumps(payload, ensure_ascii=False, indent=2) if isinstance(payload, dict) else payload
488
489 if args.out:
490 write_out(args.out, text)
491 sys.stderr.write("已写入:%s\n" % args.out)
492 if not args.json or not args.out:
493 print(text)
494 return code
495
496
497if __name__ == "__main__":
498 sys.exit(main())

文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。