31 lines
911 B
Python
31 lines
911 B
Python
"""文本裁剪等轻量工具。"""
|
||
|
||
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(",、;: ")
|