Files
daily-robots/daily/text_utils.py
2026-07-02 11:31:16 +08:00

31 lines
911 B
Python
Raw Permalink 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.

"""文本裁剪等轻量工具。"""
from __future__ import annotations
import re
_WS = re.compile(r"\s+")
def clip_text(text: str, limit: int) -> str:
text = _WS.sub(" ", (text or "").strip())
if limit <= 0 or len(text) <= limit:
return text
return text[: max(1, limit - 1)] + ""
def trim_brief(text: str, limit: int) -> str:
"""企微简要:控制在 limit 内,优先在句读处截断,不加省略号。"""
text = _WS.sub(" ", (text or "").strip())
if not text or limit <= 0 or len(text) <= limit:
return text
for sep in ("", "", "", ""):
pos = text.find(sep)
if pos != -1 and pos + 1 <= limit + 8:
return text[: pos + 1]
for sep in ("", ""):
pos = text.find(sep)
if pos != -1 and pos + 1 <= limit:
return text[: pos + 1]
return text[:limit].rstrip(",、;: ")