File size: 1,251 Bytes
22ba884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
"""Split text to limit chars per chunk.

Converted from splitText.js.
"""
# pylint: disable=invalid-name, broad-except
from typing import Optional

from logzero import logger

limit_ = 4900


def split_text(text: str, limit: Optional[int] = None):
    """Split text to limit chars per chunk."""
    if not text:  # handle text=""
        return [text]

    if limit is None:
        limit = limit_
    else:
        try:
            limit = int(limit)
        except Exception as exc:
            logger.error(exc)
            limit = limit_
    if limit < 1:
        limit = limit_

    chunks = []
    paragraphs = text.splitlines()
    current_chunk = paragraphs[0] + "\n"
    for paragraph in paragraphs[1:]:
        if len(current_chunk) + len(paragraph) <= limit:
            # Add paragraph to current chunk
            current_chunk += paragraph + "\n"
        else:
            # Save current chunk and start a new one with this paragraph
            chunks.append(current_chunk)
            current_chunk = paragraph + "\n"
    # Add the last chunk
    chunks.append(current_chunk)

    # remove extra \n and possible blank in the beginning
    # return list(filter(lambda _: _.strip(), map(lambda _: _.strip(), chunks)))

    return chunks