Files
HeXi/hexi/plugins/nonebot_plugin_bf_bot/utils/text.py
T

54 lines
1.7 KiB
Python
Raw Normal View History

"""文本/数字格式化。"""
import re
def convert_to_hours(time_str):
"""
将各种时间格式字符串转换为小时数
支持格式示例:
- "1 day, 1:49:15" (包含天数)
- "1:56:55" (小时:分钟:秒)
- "0:06:41" (分钟:秒)
- "14:11:36" (小时:分钟:秒)
接口偶尔会给带引号包裹的串(如 '"1 day, 1:49:15"'),先统一剥掉引号/空白。
"""
total_hours = 0.0
time_str = (time_str or "").strip().strip('"').strip("'")
# 处理包含天数的部分
if "day" in time_str:
days_part, time_part = time_str.split(", ")
days_match = re.search(r"\d+", days_part)
total_hours += (float(days_match.group()) if days_match else 0.0) * 24
time_str = time_part
# 分割时间部分
parts = list(map(float, time_str.split(":")))
# 根据时间部分长度计算
if len(parts) == 3: # 时:分:秒
total_hours += parts[0] + parts[1] / 60 + parts[2] / 3600
elif len(parts) == 2: # 分:秒
total_hours += parts[0] / 60 + parts[1] / 3600
elif len(parts) == 1: # 仅秒
total_hours += parts[0] / 3600
return round(total_hours, 2)
def add_commas(text):
"""给纯数字字符串加千分位,如 "1234567" -> "1,234,567"。"""
return re.sub(r"(?<!^)(?=(\d{3})+$)", ",", text)
def add_commas_with_padding(value, total_digits):
"""
固定总位数补零后,再添加千分位分隔符
:param value: 输入数字(int / str)
:param total_digits: 固定总位数(如 7)
:return: 格式化后的字符串,如 '1,234,567'
"""
text = str(value).zfill(total_digits)
return re.sub(r"(?<!^)(?=(\d{3})+$)", ",", text)