scripts/unit_convert.py
23.1 KB| 1 | #!/usr/bin/env python3 |
| 2 | """Unit converter: convert between units of length, mass, area, volume, |
| 3 | temperature, data size, speed, time, pressure, energy, power and angle. |
| 4 | |
| 5 | All conversion factors are exact definitions where such a definition exists |
| 6 | (e.g. 1 in = 0.0254 m, 1 lb = 0.45359237 kg); temperature uses affine |
| 7 | formulas. No network access, no third-party dependencies. |
| 8 | """ |
| 9 | |
| 10 | import argparse |
| 11 | import json |
| 12 | import math |
| 13 | import re |
| 14 | import sys |
| 15 | from fractions import Fraction |
| 16 | |
| 17 | MAX_PRECISION = 17 |
| 18 | DEFAULT_PRECISION = 12 |
| 19 | |
| 20 | _NUM_RE = re.compile(r"^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$") |
| 21 | |
| 22 | |
| 23 | class UnitError(Exception): |
| 24 | """Raised for problems that should exit with code 2.""" |
| 25 | |
| 26 | |
| 27 | def _linear(factor, zh, aliases): |
| 28 | f = Fraction(factor) if not isinstance(factor, Fraction) else factor |
| 29 | return { |
| 30 | "zh": zh, |
| 31 | "aliases": list(aliases), |
| 32 | "to_base": lambda v, f=f: v * float(f), |
| 33 | "from_base": lambda v, f=f: v / float(f), |
| 34 | } |
| 35 | |
| 36 | |
| 37 | def _affine(to_base, from_base, zh, aliases): |
| 38 | return { |
| 39 | "zh": zh, |
| 40 | "aliases": list(aliases), |
| 41 | "to_base": to_base, |
| 42 | "from_base": from_base, |
| 43 | } |
| 44 | |
| 45 | |
| 46 | def build_categories(): |
| 47 | cats = {} |
| 48 | |
| 49 | cats["length"] = { |
| 50 | "name": "长度", |
| 51 | "base": "m", |
| 52 | "units": { |
| 53 | "m": _linear(1, "米", ["m", "meter", "metre", "meters", "metres", "米"]), |
| 54 | "km": _linear(1000, "千米", ["km", "kilometer", "kilometre", "公里", "千米"]), |
| 55 | "cm": _linear(Fraction(1, 100), "厘米", ["cm", "centimeter", "厘米"]), |
| 56 | "mm": _linear(Fraction(1, 1000), "毫米", ["mm", "millimeter", "毫米"]), |
| 57 | "um": _linear(Fraction(1, 1000000), "微米", ["um", "μm", "µm", "micrometer", "微米"]), |
| 58 | "nm": _linear(Fraction(1, 1000000000), "纳米", ["nm", "nanometer", "纳米"]), |
| 59 | "mi": _linear(Fraction(1609344, 1000), "英里", ["mi", "mile", "miles", "英里"]), |
| 60 | "yd": _linear(Fraction(9144, 10000), "码", ["yd", "yard", "yards", "码"]), |
| 61 | "ft": _linear(Fraction(3048, 10000), "英尺", ["ft", "foot", "feet", "英尺"]), |
| 62 | "in": _linear(Fraction(254, 10000), "英寸", ["in", "inch", "inches", "英寸"]), |
| 63 | "nmi": _linear(1852, "海里", ["nmi", "nauticalmile", "海里"]), |
| 64 | "li": _linear(500, "里", ["li", "里"]), |
| 65 | }, |
| 66 | } |
| 67 | |
| 68 | cats["mass"] = { |
| 69 | "name": "质量", |
| 70 | "base": "kg", |
| 71 | "units": { |
| 72 | "kg": _linear(1, "千克", ["kg", "kilogram", "kilograms", "千克", "公斤"]), |
| 73 | "t": _linear(1000, "吨", ["t", "tonne", "ton", "tons", "吨", "公吨"]), |
| 74 | "g": _linear(Fraction(1, 1000), "克", ["g", "gram", "grams", "克"]), |
| 75 | "mg": _linear(Fraction(1, 1000000), "毫克", ["mg", "milligram", "毫克"]), |
| 76 | "ug": _linear(Fraction(1, 1000000000), "微克", ["ug", "μg", "µg", "microgram", "微克"]), |
| 77 | "lb": _linear(Fraction(45359237, 100000000), "磅", ["lb", "lbs", "pound", "pounds", "磅"]), |
| 78 | "oz": _linear(Fraction(45359237, 1600000000), "盎司", ["oz", "ounce", "ounces", "盎司"]), |
| 79 | "jin": _linear(Fraction(1, 2), "斤", ["jin", "斤", "市斤"]), |
| 80 | "liang": _linear(Fraction(1, 20), "两", ["liang", "两"]), |
| 81 | "ct": _linear(Fraction(1, 5000), "克拉", ["ct", "carat", "克拉"]), |
| 82 | "st": _linear(Fraction(635029318, 100000000), "英石", ["st", "stone", "英石"]), |
| 83 | }, |
| 84 | } |
| 85 | |
| 86 | cats["area"] = { |
| 87 | "name": "面积", |
| 88 | "base": "m2", |
| 89 | "units": { |
| 90 | "m2": _linear(1, "平方米", ["m2", "sqm", "平方米", "平米"]), |
| 91 | "km2": _linear(1000000, "平方千米", ["km2", "平方千米", "平方公里"]), |
| 92 | "cm2": _linear(Fraction(1, 10000), "平方厘米", ["cm2", "平方厘米"]), |
| 93 | "mm2": _linear(Fraction(1, 1000000), "平方毫米", ["mm2", "平方毫米"]), |
| 94 | "ha": _linear(10000, "公顷", ["ha", "hectare", "公顷"]), |
| 95 | "acre": _linear(Fraction(40468564224, 10000000), "英亩", ["acre", "acres", "英亩"]), |
| 96 | "mu": _linear(Fraction(10000, 15), "亩", ["mu", "亩", "市亩"]), |
| 97 | "ft2": _linear(Fraction(9290304, 100000000), "平方英尺", ["ft2", "sqft", "平方英尺"]), |
| 98 | "in2": _linear(Fraction(64516, 100000000), "平方英寸", ["in2", "平方英寸"]), |
| 99 | "mi2": _linear(Fraction(2589988110336, 1000000), "平方英里", ["mi2", "平方英里"]), |
| 100 | }, |
| 101 | } |
| 102 | |
| 103 | cats["volume"] = { |
| 104 | "name": "体积", |
| 105 | "base": "L", |
| 106 | "units": { |
| 107 | "L": _linear(1, "升", ["l", "L", "liter", "litre", "liters", "升"]), |
| 108 | "mL": _linear(Fraction(1, 1000), "毫升", ["ml", "mL", "milliliter", "毫升"]), |
| 109 | "m3": _linear(1000, "立方米", ["m3", "立方米", "方"]), |
| 110 | "cm3": _linear(Fraction(1, 1000), "立方厘米", ["cm3", "cc", "立方厘米"]), |
| 111 | "mm3": _linear(Fraction(1, 1000000), "立方毫米", ["mm3", "立方毫米"]), |
| 112 | "gal": _linear(Fraction(3785411784, 1000000000), "美制加仑", ["gal", "gallon", "gallons", "加仑", "美制加仑"]), |
| 113 | "qt": _linear(Fraction(946352946, 1000000000), "美制夸脱", ["qt", "quart", "夸脱"]), |
| 114 | "pt": _linear(Fraction(473176473, 1000000000), "美制品脱", ["pt", "pint", "品脱"]), |
| 115 | "floz": _linear(Fraction(295735295625, 10000000000000), "美制液盎司", ["floz", "fluidounce", "液盎司"]), |
| 116 | "gal_uk": _linear(Fraction(454609, 100000), "英制加仑", ["gal_uk", "英制加仑"]), |
| 117 | }, |
| 118 | } |
| 119 | |
| 120 | cats["temperature"] = { |
| 121 | "name": "温度", |
| 122 | "base": "C", |
| 123 | "units": { |
| 124 | "C": _affine(lambda v: v, lambda v: v, "摄氏度", ["c", "C", "celsius", "摄氏", "摄氏度", "°c"]), |
| 125 | "F": _affine(lambda v: (v - 32) * 5 / 9, lambda v: v * 9 / 5 + 32, "华氏度", ["f", "F", "fahrenheit", "华氏", "华氏度", "°f"]), |
| 126 | "K": _affine(lambda v: v - 273.15, lambda v: v + 273.15, "开尔文", ["k", "K", "kelvin", "开尔文", "开"]), |
| 127 | "R": _affine(lambda v: v * 5 / 9 - 273.15, lambda v: (v + 273.15) * 9 / 5, "兰氏度", ["r", "R", "rankine", "兰氏度"]), |
| 128 | }, |
| 129 | } |
| 130 | |
| 131 | cats["data"] = { |
| 132 | "name": "数据存储", |
| 133 | "base": "B", |
| 134 | "units": { |
| 135 | "B": _linear(1, "字节", ["b_byte", "byte", "bytes", "字节", "B"]), |
| 136 | "bit": _linear(Fraction(1, 8), "比特", ["bit", "bits", "b", "比特", "位"]), |
| 137 | "KB": _linear(1000, "千字节", ["kb", "KB", "kilobyte", "千字节"]), |
| 138 | "KiB": _linear(1024, "二进制千字节", ["kib", "KiB", "kibibyte"]), |
| 139 | "MB": _linear(1000000, "兆字节", ["mb", "MB", "megabyte", "兆字节", "兆"]), |
| 140 | "MiB": _linear(1048576, "二进制兆字节", ["mib", "MiB", "mebibyte"]), |
| 141 | "GB": _linear(1000000000, "吉字节", ["gb", "GB", "gigabyte", "吉字节"]), |
| 142 | "GiB": _linear(1073741824, "二进制吉字节", ["gib", "GiB", "gibibyte"]), |
| 143 | "TB": _linear(1000000000000, "太字节", ["tb", "TB", "terabyte", "太字节"]), |
| 144 | "TiB": _linear(1099511627776, "二进制太字节", ["tib", "TiB", "tebibyte"]), |
| 145 | "PB": _linear(1000000000000000, "拍字节", ["pb", "PB", "petabyte", "拍字节"]), |
| 146 | }, |
| 147 | } |
| 148 | |
| 149 | cats["speed"] = { |
| 150 | "name": "速度", |
| 151 | "base": "m/s", |
| 152 | "units": { |
| 153 | "m/s": _linear(1, "米每秒", ["m/s", "mps", "米每秒", "米/秒"]), |
| 154 | "km/h": _linear(Fraction(1, 3600) * 1000, "千米每小时", ["km/h", "kph", "kmh", "千米每小时", "公里每小时", "公里/小时"]), |
| 155 | "mph": _linear(Fraction(44704, 100000), "英里每小时", ["mph", "英里每小时", "迈"]), |
| 156 | "kn": _linear(Fraction(1852, 3600), "节", ["kn", "knot", "knots", "节"]), |
| 157 | "ft/s": _linear(Fraction(3048, 10000), "英尺每秒", ["ft/s", "fps", "英尺每秒"]), |
| 158 | }, |
| 159 | } |
| 160 | |
| 161 | cats["time"] = { |
| 162 | "name": "时间", |
| 163 | "base": "s", |
| 164 | "units": { |
| 165 | "s": _linear(1, "秒", ["s", "sec", "second", "seconds", "秒"]), |
| 166 | "ms": _linear(Fraction(1, 1000), "毫秒", ["ms", "millisecond", "毫秒"]), |
| 167 | "us": _linear(Fraction(1, 1000000), "微秒", ["us", "μs", "µs", "microsecond", "微秒"]), |
| 168 | "ns": _linear(Fraction(1, 1000000000), "纳秒", ["ns", "nanosecond", "纳秒"]), |
| 169 | "min": _linear(60, "分钟", ["min", "minute", "minutes", "分钟", "分"]), |
| 170 | "h": _linear(3600, "小时", ["h", "hr", "hour", "hours", "小时", "时"]), |
| 171 | "d": _linear(86400, "天", ["d", "day", "days", "天", "日"]), |
| 172 | "week": _linear(604800, "周", ["week", "weeks", "周", "星期"]), |
| 173 | "year365": _linear(31536000, "年(365 天)", ["year", "years", "year365", "年"]), |
| 174 | }, |
| 175 | } |
| 176 | |
| 177 | cats["pressure"] = { |
| 178 | "name": "压强", |
| 179 | "base": "Pa", |
| 180 | "units": { |
| 181 | "Pa": _linear(1, "帕斯卡", ["pa", "Pa", "pascal", "帕", "帕斯卡"]), |
| 182 | "kPa": _linear(1000, "千帕", ["kpa", "kPa", "千帕"]), |
| 183 | "MPa": _linear(1000000, "兆帕", ["mpa", "MPa", "兆帕"]), |
| 184 | "bar": _linear(100000, "巴", ["bar", "bars", "巴"]), |
| 185 | "atm": _linear(101325, "标准大气压", ["atm", "atmosphere", "大气压", "标准大气压"]), |
| 186 | "psi": _linear(Fraction(6894757293, 1000000), "磅每平方英寸", ["psi", "磅每平方英寸"]), |
| 187 | "mmHg": _linear(133.322387415, "毫米汞柱", ["mmhg", "mmHg", "毫米汞柱"]), |
| 188 | "torr": _linear(Fraction(101325, 760), "托", ["torr", "托"]), |
| 189 | }, |
| 190 | } |
| 191 | |
| 192 | cats["energy"] = { |
| 193 | "name": "能量", |
| 194 | "base": "J", |
| 195 | "units": { |
| 196 | "J": _linear(1, "焦耳", ["j", "J", "joule", "焦耳", "焦"]), |
| 197 | "kJ": _linear(1000, "千焦", ["kj", "kJ", "千焦", "千焦耳"]), |
| 198 | "cal": _linear(Fraction(4184, 1000), "卡", ["cal", "calorie", "calories", "卡", "卡路里"]), |
| 199 | "kcal": _linear(4184, "千卡", ["kcal", "千卡", "大卡"]), |
| 200 | "Wh": _linear(3600, "瓦时", ["wh", "Wh", "瓦时"]), |
| 201 | "kWh": _linear(3600000, "千瓦时", ["kwh", "kWh", "千瓦时"]), |
| 202 | "eV": _linear(Fraction(1602176634, 10 ** 28), "电子伏", ["ev", "eV", "电子伏"]), |
| 203 | }, |
| 204 | } |
| 205 | |
| 206 | cats["power"] = { |
| 207 | "name": "功率", |
| 208 | "base": "W", |
| 209 | "units": { |
| 210 | "W": _linear(1, "瓦", ["w", "W", "watt", "瓦", "瓦特"]), |
| 211 | "kW": _linear(1000, "千瓦", ["kw", "kW", "千瓦"]), |
| 212 | "MW": _linear(1000000, "兆瓦", ["mw", "MW", "兆瓦"]), |
| 213 | "hp": _linear(Fraction(745699871582, 1000000000), "马力(机械)", ["hp", "horsepower", "马力"]), |
| 214 | }, |
| 215 | } |
| 216 | |
| 217 | cats["angle"] = { |
| 218 | "name": "角度", |
| 219 | "base": "rad", |
| 220 | "units": { |
| 221 | "rad": _linear(1, "弧度", ["rad", "radian", "弧度"]), |
| 222 | "deg": {"zh": "度", "aliases": ["deg", "degree", "degrees", "度", "°"], |
| 223 | "to_base": lambda v: math.radians(v), "from_base": lambda v: math.degrees(v)}, |
| 224 | "grad": _linear(math.pi / 200, "百分度", ["grad", "gradian", "百分度"]), |
| 225 | }, |
| 226 | } |
| 227 | |
| 228 | return cats |
| 229 | |
| 230 | |
| 231 | CATEGORIES = build_categories() |
| 232 | |
| 233 | |
| 234 | def build_alias_index(): |
| 235 | exact = {} |
| 236 | lower = {} |
| 237 | for cat, info in CATEGORIES.items(): |
| 238 | for uid, unit in info["units"].items(): |
| 239 | for alias in unit["aliases"] + [uid]: |
| 240 | exact.setdefault(alias, []).append((cat, uid)) |
| 241 | lower.setdefault(alias.lower(), []).append((cat, uid)) |
| 242 | return exact, lower |
| 243 | |
| 244 | |
| 245 | EXACT_INDEX, LOWER_INDEX = build_alias_index() |
| 246 | |
| 247 | |
| 248 | def resolve_unit(name, category=None): |
| 249 | """Return (category, unit_id) for a unit name, or raise UnitError.""" |
| 250 | key = name.strip() |
| 251 | if not key: |
| 252 | raise UnitError("单位名为空") |
| 253 | |
| 254 | candidates = EXACT_INDEX.get(key) |
| 255 | if not candidates: |
| 256 | candidates = LOWER_INDEX.get(key.lower()) |
| 257 | if not candidates: |
| 258 | raise UnitError("不认识单位「%s」" % key) |
| 259 | |
| 260 | if category: |
| 261 | for cat, uid in candidates: |
| 262 | if cat == category: |
| 263 | return cat, uid |
| 264 | raise UnitError("单位「%s」不属于 %s(%s)" % (key, category, CATEGORIES[category]["name"])) |
| 265 | |
| 266 | cats = sorted({c for c, _ in candidates}) |
| 267 | if len(cats) > 1: |
| 268 | names = "、".join("%s(%s)" % (c, CATEGORIES[c]["name"]) for c in cats) |
| 269 | raise UnitError("单位「%s」在多个分类中都存在(%s),请用 --category 指定" % (key, names)) |
| 270 | return candidates[0] |
| 271 | |
| 272 | |
| 273 | def auto_category(from_name, to_name, explicit=None): |
| 274 | if explicit: |
| 275 | if explicit not in CATEGORIES: |
| 276 | raise UnitError("未知分类「%s」,可用:%s" % (explicit, "、".join(CATEGORIES))) |
| 277 | return explicit |
| 278 | |
| 279 | sets = [] |
| 280 | for name in (from_name, to_name): |
| 281 | key = name.strip() |
| 282 | cands = EXACT_INDEX.get(key) or LOWER_INDEX.get(key.lower()) |
| 283 | if not cands: |
| 284 | raise UnitError("不认识单位「%s」" % key) |
| 285 | sets.append({c for c, _ in cands}) |
| 286 | |
| 287 | common = sets[0] & sets[1] |
| 288 | if not common: |
| 289 | raise UnitError("「%s」和「%s」不属于同一个分类" % (from_name, to_name)) |
| 290 | if len(common) > 1: |
| 291 | names = "、".join("%s(%s)" % (c, CATEGORIES[c]["name"]) for c in sorted(common)) |
| 292 | raise UnitError("这两个单位可能在多个分类中匹配(%s),请用 --category 指定" % names) |
| 293 | return sorted(common)[0] |
| 294 | |
| 295 | |
| 296 | def parse_number(text): |
| 297 | s = text.strip().replace("_", "") |
| 298 | if not s: |
| 299 | raise UnitError("数值为空") |
| 300 | if not _NUM_RE.match(s): |
| 301 | raise UnitError("「%s」不是可识别的数值(支持 12、-3.5、1.2e-3,不支持千分位逗号)" % text.strip()) |
| 302 | value = float(s) |
| 303 | if math.isinf(value) or math.isnan(value): |
| 304 | raise UnitError("数值超出范围:%s" % text.strip()) |
| 305 | return value |
| 306 | |
| 307 | |
| 308 | def fmt(value, precision=DEFAULT_PRECISION): |
| 309 | if value == 0: |
| 310 | return "0" |
| 311 | text = ("%." + str(precision) + "g") % value |
| 312 | if text == "-0": |
| 313 | text = "0" |
| 314 | if "e" in text: |
| 315 | mantissa, exp = text.split("e") |
| 316 | exp = int(exp) |
| 317 | text = "%se%s%d" % (mantissa, "+" if exp >= 0 else "-", abs(exp)) |
| 318 | return text |
| 319 | |
| 320 | |
| 321 | def convert(value, category, from_unit, to_unit, precision=DEFAULT_PRECISION): |
| 322 | info = CATEGORIES[category] |
| 323 | f = info["units"][from_unit] |
| 324 | t = info["units"][to_unit] |
| 325 | |
| 326 | base = f["to_base"](value) |
| 327 | result = t["from_base"](base) |
| 328 | |
| 329 | warnings = [] |
| 330 | if category == "temperature": |
| 331 | if from_unit not in ("K",) and base < -273.15: |
| 332 | warnings.append("换算到摄氏度后低于绝对零度(-273.15 °C),物理上不成立") |
| 333 | if result < 0 and to_unit == "K": |
| 334 | warnings.append("结果低于 0 K,物理上不成立") |
| 335 | |
| 336 | return { |
| 337 | "value": value, |
| 338 | "category": category, |
| 339 | "from": from_unit, |
| 340 | "to": to_unit, |
| 341 | "base_value": base, |
| 342 | "result": result, |
| 343 | "result_text": fmt(result, precision) + " " + to_unit, |
| 344 | "precision": precision, |
| 345 | "warnings": warnings, |
| 346 | } |
| 347 | |
| 348 | |
| 349 | def describe(category, uid): |
| 350 | unit = CATEGORIES[category]["units"][uid] |
| 351 | return "%s(%s)" % (unit["zh"], uid) |
| 352 | |
| 353 | |
| 354 | def do_convert(args): |
| 355 | category = auto_category(args.from_unit, args.to_unit, args.category) |
| 356 | cat, from_unit = resolve_unit(args.from_unit, category) |
| 357 | _, to_unit = resolve_unit(args.to_unit, category) |
| 358 | value = parse_number(args.value) |
| 359 | precision = args.precision |
| 360 | |
| 361 | r = convert(value, category, from_unit, to_unit, precision) |
| 362 | |
| 363 | if args.json: |
| 364 | return 0, { |
| 365 | "action": "convert", |
| 366 | "input": {"value": args.value, "from": args.from_unit, "to": args.to_unit}, |
| 367 | "category": category, |
| 368 | "category_name": CATEGORIES[category]["name"], |
| 369 | "from_unit": from_unit, |
| 370 | "to_unit": to_unit, |
| 371 | "from_desc": describe(category, from_unit), |
| 372 | "to_desc": describe(category, to_unit), |
| 373 | "result": r["result"], |
| 374 | "result_text": r["result_text"], |
| 375 | "warnings": r["warnings"], |
| 376 | } |
| 377 | |
| 378 | lines = [ |
| 379 | "%s %s → %s" % (fmt(value, precision), describe(category, from_unit), describe(category, to_unit)), |
| 380 | "结果:%s" % r["result_text"], |
| 381 | "分类:%s(%s)" % (CATEGORIES[category]["name"], category), |
| 382 | "精度:%d 位有效数字" % precision, |
| 383 | ] |
| 384 | if r["warnings"]: |
| 385 | lines.append("提示:") |
| 386 | lines.extend(" - " + w for w in r["warnings"]) |
| 387 | return 0, "\n".join(lines) |
| 388 | |
| 389 | |
| 390 | def do_list(args): |
| 391 | cats = [args.category] if args.category else list(CATEGORIES) |
| 392 | for c in cats: |
| 393 | if c not in CATEGORIES: |
| 394 | raise UnitError("未知分类「%s」,可用:%s" % (c, "、".join(CATEGORIES))) |
| 395 | |
| 396 | if args.json: |
| 397 | data = {"action": "list", "categories": []} |
| 398 | for c in cats: |
| 399 | info = CATEGORIES[c] |
| 400 | data["categories"].append({ |
| 401 | "category": c, |
| 402 | "name": info["name"], |
| 403 | "base": info["base"], |
| 404 | "units": [ |
| 405 | {"unit": uid, "name": u["zh"], "aliases": u["aliases"]} |
| 406 | for uid, u in info["units"].items() |
| 407 | ], |
| 408 | }) |
| 409 | return 0, data |
| 410 | |
| 411 | out = [] |
| 412 | for c in cats: |
| 413 | info = CATEGORIES[c] |
| 414 | out.append("%s(%s),基准单位 %s" % (info["name"], c, info["base"])) |
| 415 | for uid, u in info["units"].items(): |
| 416 | aliases = [a for a in u["aliases"] if a.lower() != uid.lower()] |
| 417 | line = " %-8s %s" % (uid, u["zh"]) |
| 418 | if aliases: |
| 419 | line += "(别名:%s)" % "、".join(aliases[:6]) |
| 420 | out.append(line) |
| 421 | out.append("") |
| 422 | return 0, "\n".join(out).rstrip() |
| 423 | |
| 424 | |
| 425 | SEP_RE = re.compile(r"\s*(?:->|=>|→|\bto\b|转成|换成|换算成|换算为|换算|转)\s*", re.IGNORECASE) |
| 426 | LEFT_RE = re.compile(r"^([+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$") |
| 427 | |
| 428 | |
| 429 | def parse_batch_line(line, precision=DEFAULT_PRECISION): |
| 430 | raw = line.strip() |
| 431 | if not raw or raw.startswith("#"): |
| 432 | return None |
| 433 | |
| 434 | parts = SEP_RE.split(raw, maxsplit=1) |
| 435 | if len(parts) != 2: |
| 436 | raise UnitError("格式应为「数值 单位 -> 单位」,例如「1.5 km -> m」") |
| 437 | |
| 438 | left, right = parts[0].strip(), parts[1].strip() |
| 439 | m = LEFT_RE.match(left) |
| 440 | if not m: |
| 441 | raise UnitError("左侧应该是「数值 单位」,例如「1.5 km」") |
| 442 | num_text, from_text = m.group(1), m.group(2).strip() |
| 443 | to_text = right.strip() |
| 444 | |
| 445 | if not from_text: |
| 446 | raise UnitError("左侧缺少来源单位") |
| 447 | if not to_text: |
| 448 | raise UnitError("右侧缺少目标单位") |
| 449 | |
| 450 | category = auto_category(from_text, to_text) |
| 451 | _, from_unit = resolve_unit(from_text, category) |
| 452 | _, to_unit = resolve_unit(to_text, category) |
| 453 | value = parse_number(num_text) |
| 454 | r = convert(value, category, from_unit, to_unit, precision) |
| 455 | |
| 456 | return { |
| 457 | "line": raw, |
| 458 | "value": value, |
| 459 | "from": from_unit, |
| 460 | "to": to_unit, |
| 461 | "category": category, |
| 462 | "result": r["result"], |
| 463 | "result_text": r["result_text"], |
| 464 | "warnings": r["warnings"], |
| 465 | } |
| 466 | |
| 467 | |
| 468 | def do_batch(args): |
| 469 | lines = [] |
| 470 | if args.file: |
| 471 | try: |
| 472 | with open(args.file, "r", encoding="utf-8-sig") as fh: |
| 473 | lines.extend(fh.read().splitlines()) |
| 474 | except OSError as exc: |
| 475 | raise UnitError("读不了文件:%s" % exc) |
| 476 | if args.line: |
| 477 | lines.extend(args.line) |
| 478 | if not lines: |
| 479 | raise UnitError("没有要换算的内容,用 --file 或 --line 给出") |
| 480 | |
| 481 | ok = [] |
| 482 | failed = [] |
| 483 | total = 0 |
| 484 | for idx, line in enumerate(lines, start=1): |
| 485 | if not line.strip() or line.strip().startswith("#"): |
| 486 | continue |
| 487 | total += 1 |
| 488 | try: |
| 489 | item = parse_batch_line(line, args.precision) |
| 490 | except UnitError as exc: |
| 491 | failed.append({"index": idx, "line": line.strip(), "error": str(exc)}) |
| 492 | continue |
| 493 | if item: |
| 494 | ok.append(item) |
| 495 | |
| 496 | code = 0 if not failed else 2 |
| 497 | |
| 498 | if args.json: |
| 499 | return code, { |
| 500 | "action": "batch", |
| 501 | "total": total, |
| 502 | "ok": len(ok), |
| 503 | "failed": len(failed), |
| 504 | "items": ok, |
| 505 | "errors": failed, |
| 506 | } |
| 507 | |
| 508 | out = [] |
| 509 | for item in ok: |
| 510 | out.append("%s %s -> %s = %s" % ( |
| 511 | fmt(item["value"], args.precision), item["from"], item["to"], item["result_text"])) |
| 512 | for w in item["warnings"]: |
| 513 | out.append(" 提示:" + w) |
| 514 | if failed: |
| 515 | out.append("") |
| 516 | out.append("未换算的行:") |
| 517 | for f in failed: |
| 518 | out.append(" 第 %d 行 %s:%s" % (f["index"], f["line"], f["error"])) |
| 519 | out.append("") |
| 520 | out.append("合计 %d 行,成功 %d,失败 %d" % (total, len(ok), len(failed))) |
| 521 | return code, "\n".join(out) |
| 522 | |
| 523 | |
| 524 | def write_out(path, text): |
| 525 | with open(path, "w", encoding="utf-8", newline="\n") as fh: |
| 526 | fh.write(text if text.endswith("\n") else text + "\n") |
| 527 | |
| 528 | |
| 529 | def build_parser(): |
| 530 | p = argparse.ArgumentParser( |
| 531 | prog="unit_convert.py", |
| 532 | description="单位换算:长度、质量、面积、体积、温度、数据存储、速度、时间、压强、能量、功率、角度。", |
| 533 | ) |
| 534 | sub = p.add_subparsers(dest="action", required=True) |
| 535 | |
| 536 | def add_common(sp, need_category=True): |
| 537 | sp.add_argument("--precision", type=int, default=DEFAULT_PRECISION, |
| 538 | help="结果的有效数字位数(1-%d,默认 %d)" % (MAX_PRECISION, DEFAULT_PRECISION)) |
| 539 | sp.add_argument("--json", action="store_true", help="输出 JSON") |
| 540 | sp.add_argument("--out", help="把结果写入文件(UTF-8)") |
| 541 | |
| 542 | cv = sub.add_parser("convert", help="换算一个值") |
| 543 | cv.add_argument("--value", required=True, help="数值,例如 1.5 或 3e4") |
| 544 | cv.add_argument("--from", dest="from_unit", required=True, help="来源单位,例如 km") |
| 545 | cv.add_argument("--to", dest="to_unit", required=True, help="目标单位,例如 m") |
| 546 | cv.add_argument("--category", help="分类,单位有歧义时指定") |
| 547 | add_common(cv) |
| 548 | |
| 549 | ls = sub.add_parser("list", help="列出支持的单位") |
| 550 | ls.add_argument("--category", help="只列某一类") |
| 551 | add_common(ls) |
| 552 | |
| 553 | bt = sub.add_parser("batch", help="批量换算,每行「数值 单位 -> 单位」") |
| 554 | bt.add_argument("--file", help="从文件读取(UTF-8)") |
| 555 | bt.add_argument("--line", action="append", help="直接给一行,可重复") |
| 556 | add_common(bt) |
| 557 | |
| 558 | return p |
| 559 | |
| 560 | |
| 561 | def main(argv=None): |
| 562 | parser = build_parser() |
| 563 | args = parser.parse_args(argv) |
| 564 | |
| 565 | if args.precision < 1 or args.precision > MAX_PRECISION: |
| 566 | sys.stderr.write("错误:--precision 必须在 1 到 %d 之间\n" % MAX_PRECISION) |
| 567 | return 2 |
| 568 | |
| 569 | try: |
| 570 | if args.action == "convert": |
| 571 | code, payload = do_convert(args) |
| 572 | elif args.action == "list": |
| 573 | code, payload = do_list(args) |
| 574 | else: |
| 575 | code, payload = do_batch(args) |
| 576 | except UnitError as exc: |
| 577 | sys.stderr.write("错误:%s\n" % exc) |
| 578 | return 2 |
| 579 | |
| 580 | if isinstance(payload, dict): |
| 581 | text = json.dumps(payload, ensure_ascii=False, indent=2) |
| 582 | else: |
| 583 | text = payload |
| 584 | |
| 585 | if args.out: |
| 586 | write_out(args.out, text) |
| 587 | sys.stderr.write("已写入:%s\n" % args.out) |
| 588 | if not args.json or not args.out: |
| 589 | print(text) |
| 590 | return code |
| 591 | |
| 592 | |
| 593 | if __name__ == "__main__": |
| 594 | sys.exit(main()) |
文件内容是平台检查时读出的文本,只供查看。平台不会运行包里的任何脚本或程序。

