MCPcopy
hub / github.com/1Panel-dev/MaxKB / smart_split_paragraph

Function smart_split_paragraph

apps/common/utils/split_model.py:297–344  ·  view source on GitHub ↗

智能分段:在limit前找到合适的分割点(句号、回车等) :param content: 需要分段的文本 :param limit: 最大字符限制 :return: 分段后的文本列表

(content: str, limit: int)

Source from the content-addressed store, hash-verified

295
296
297def smart_split_paragraph(content: str, limit: int):
298 """
299 智能分段:在limit前找到合适的分割点(句号、回车等)
300 :param content: 需要分段的文本
301 :param limit: 最大字符限制
302 :return: 分段后的文本列表
303 """
304 if len(content) <= limit:
305 return [content]
306
307 result = []
308 start = 0
309
310 while start < len(content):
311 end = start + limit
312
313 if end >= len(content):
314 # 剩余文本不超过限制,直接添加
315 result.append(content[start:])
316 break
317
318 # 在limit范围内寻找最佳分割点
319 best_split = end
320
321 # 优先级:句号 > 感叹号/问号 > 回车
322 split_chars = [
323 ('。', 0), ('.', 0), # 中英文句号
324 ('!', 0), ('!', 0), # 中英文感叹号
325 ('?', 0), ('?', 0), # 中英文问号
326 ]
327
328 # 从后往前找分割点
329 for i in range(end - 1, start + limit // 2, -1): # 至少保留一半内容
330 for char, offset in split_chars:
331 if content[i] == char:
332 best_split = i + 1 # 包含分隔符在当前段
333 break
334 if best_split != end:
335 break
336
337 # 如果找不到合适分割点,使用原始limit
338 if best_split == end and end < len(content):
339 best_split = end
340
341 result.append(content[start:best_split])
342 start = best_split
343
344 return [text for text in result if text.strip()]
345
346
347replace_map = {

Callers 3

handle_tocMethod · 0.90
handle_linksMethod · 0.90
parse_to_treeMethod · 0.85

Calls 1

appendMethod · 0.45

Tested by

no test coverage detected