57 lines
1.6 KiB
Python
57 lines
1.6 KiB
Python
"""文字 / 顏色 / 檔名 / 數字格式化工具。
|
||
|
||
從 app.py 抽出的純函數,無外部副作用。
|
||
"""
|
||
import hashlib
|
||
import re
|
||
from datetime import datetime
|
||
|
||
|
||
def slugify(text):
|
||
"""將任意字串轉為適合用於 HTML id / URL 的 slug。"""
|
||
if not text:
|
||
return ""
|
||
return (
|
||
str(text)
|
||
.replace(' ', '_')
|
||
.replace(':', '')
|
||
.replace('!', '')
|
||
.replace('?', '')
|
||
.replace('/', '')
|
||
.replace('&', '')
|
||
.replace('(', '')
|
||
.replace(')', '')
|
||
.replace('+', '_')
|
||
.replace('.', '_')
|
||
.replace('%', '')
|
||
.replace("'", "")
|
||
)
|
||
|
||
|
||
def get_color_for_string(s):
|
||
"""為字串生成一個穩定且美觀的 HSL 顏色(柔和淺色,適合背景)。"""
|
||
if not s:
|
||
return "hsl(0, 0%, 85%)" # 預設灰色
|
||
hash_val = int(hashlib.md5(s.encode('utf-8'), usedforsecurity=False).hexdigest(), 16)
|
||
hue = hash_val % 360
|
||
return f"hsl({hue}, 60%, 88%)"
|
||
|
||
|
||
def extract_snapshot_date_from_filename(filename):
|
||
"""從檔名提取 8 碼日期:即時業績_當日_20260111.xlsx → 2026-01-11。"""
|
||
match = re.search(r'(\d{8})', filename)
|
||
if not match:
|
||
return None
|
||
date_str = match.group(1)
|
||
try:
|
||
return datetime.strptime(date_str, "%Y%m%d").date().isoformat()
|
||
except ValueError:
|
||
return None
|
||
|
||
|
||
def number_format(value):
|
||
"""將數字格式化,加上千分位符號(無小數)。非數字直接回傳原值。"""
|
||
if isinstance(value, (int, float)):
|
||
return "{:,.0f}".format(value)
|
||
return value
|