refactor: 抽取倒计时解析工具到 time_utils 模块
将散落在三处的重复 _parse_mm_ss / _extract_2digits 实现集中到 douyin/utils/time_utils.py,便于复用与单元测试。 不修改既有调用点(保持向后兼容),后续可按需迁移。 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
61d72b2b8d
commit
68a2ab73ba
1 file changed
+61
@@ -0,0 +1,61 @@
|
||||
"""倒计时解析与时间相关的工具函数。
|
||||
|
||||
集中化以前散落在多个文件的重复实现:
|
||||
- douyin/fudai/douyin_fudai_core.py: _parse_mm_ss
|
||||
- douyin/fudai/core/fudai_detail_reader.py: _parse_mm_ss
|
||||
- fudai_detail_modules/fudai_detail_reader.py: _parse_mm_ss
|
||||
|
||||
注意:normalize_countdown_text 仍在 douyin/utils/douyin_utils.py 中,
|
||||
那里逻辑更复杂(包含 OCR 字符纠正等),不在此处重复。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Optional, Tuple
|
||||
|
||||
|
||||
def parse_mm_ss(text: str) -> Optional[Tuple[int, int]]:
|
||||
"""从文本中解析 mm:ss 格式的时间,返回 (分钟, 秒) 元组。
|
||||
|
||||
支持中文冒号 `:` 和英文冒号 `:`。
|
||||
|
||||
Args:
|
||||
text: 待解析的文本,例如 "11:37" 或 "5:30后开奖"
|
||||
|
||||
Returns:
|
||||
成功返回 (mm, ss) 元组;失败返回 None
|
||||
"""
|
||||
if not text:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})[::](\d{2})", str(text))
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
return int(m.group(1)), int(m.group(2))
|
||||
except (ValueError, TypeError) as e:
|
||||
logging.debug("解析倒计时格式失败: text=%r, error=%s", str(text)[:50], e)
|
||||
return None
|
||||
|
||||
|
||||
def extract_2digits(text: str) -> str:
|
||||
"""从文本中提取最多 2 位数字。
|
||||
|
||||
用于 OCR 倒计时分钟段/秒段的预处理。
|
||||
|
||||
Args:
|
||||
text: OCR 识别的文本
|
||||
|
||||
Returns:
|
||||
2 位数字字符串;不足 2 位时左侧补 0;无数字返回空串
|
||||
"""
|
||||
digits = "".join(ch for ch in str(text or "") if ch.isdigit())
|
||||
if len(digits) >= 2:
|
||||
return digits[:2]
|
||||
if len(digits) == 1:
|
||||
return "0" + digits
|
||||
return ""
|
||||
|
||||
|
||||
__all__ = ["parse_mm_ss", "extract_2digits"]
|
||||
Reference in new issue
Block a user