Как разбить большой текст на несколько частей?
import random
text = ""
rand_range = random.randint(2000, 10000)
for i in range(rand_range):
text += str(i)
Есть чат в котором ограничение на длину сообщений в 2000 символов и есть бот, который должен отправить в этот чат сообщение превышающее эту длину. Как можно разбить текст на несколько сообщений по 2000 символов?
Ответы (1 шт):
Автор решения: Кирилл Куренков
→ Ссылка
Не могу комментарий оставить, оставлю кусок кода которым можно пользоваться
def split_text_1(text: str, max_chars: int = 2000) -> list:
"""
Разделяет текст по словам (разделитель - пробел)
:param text: Текст
:param max_chars: Максимально допустимая длина части текста
"""
result = []
text_words = text.split(' ')
temp = text_words[0]
for word in text_words[1:]:
if len(temp + word) > max_chars:
result.append(temp)
temp = word
else:
temp += f' {word}'
result.append(temp)
return result
def split_text_2(text: str, max_chars: int = 2000) -> list:
"""
Разделяет текст по символам
:param text: Текст
:param max_chars: Максимально допустимая длина части текста
"""
result = [text[i:i + max_chars] for i in range(0, len(text), max_chars)]
return result
text_sample = '''Founded in 2008, Stack Overflow’s public platform is used by nearly everyone who codes to learn,
share their knowledge, collaborate, and build their careers.
Our products and tools help developers and technologists in life and at work.
These products include Stack Overflow for Teams, Stack Overflow Advertising, and Stack Overflow for Talent and Jobs.'''
print(split_text_1(text_sample, max_chars=100))
print(split_text_2(text_sample, max_chars=100))