Files
ewoooc/utils/text_helpers.py
ooo 0a3f6cb22d
All checks were successful
CD Pipeline / deploy (push) Successful in 1m7s
refactor(p1-01b): app.py 文字/顏色/數字工具抽到 utils/text_helpers.py
- slugify, get_color_for_string, extract_snapshot_date_from_filename, number_format
- @app.template_filter('number_format') 保留為 Jinja 註冊薄殼,實作走 utils
- app.py: 7,206 → 7,187 (-19)
2026-04-28 15:44:15 +08:00

59 lines
1.6 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.
"""文字 / 顏色 / 檔名 / 數字格式化工具。
從 app.py 抽出的純函數,無外部副作用。
"""
import hashlib
import re
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:
year = date_str[:4]
month = date_str[4:6]
day = date_str[6:8]
return f"{year}-{month}-{day}"
except Exception:
return None
def number_format(value):
"""將數字格式化,加上千分位符號(無小數)。非數字直接回傳原值。"""
if isinstance(value, (int, float)):
return "{:,.0f}".format(value)
return value