Методы Python для разделения строк точкой или восклицательным знаком

Чтобы разделить строки в Python по точкам (.) или восклицательным знакам (!) и распечатать их по отдельности, вы можете использовать различные методы. Вот несколько подходов:

Метод 1: использование функции Split()

text = "Hello! How are you? I am fine. Great!"
sentences = text.split('. ')  # Splitting based on period followed by a space
sentences = [sentence.strip() for sentence in sentences]  # Removing leading/trailing spaces
for sentence in sentences:
    print(sentence)

Метод 2. Использование регулярных выражений (regex)

import re
text = "Hello! How are you? I am fine. Great!"
sentences = re.split(r'\. |\! ', text)  # Splitting based on period or exclamation mark followed by a space
sentences = [sentence.strip() for sentence in sentences]  # Removing leading/trailing spaces
for sentence in sentences:
    print(sentence)

Способ 3. Использование библиотеки nltk (требуется установка)

import nltk
nltk.download('punkt')  # Downloading the required model/tokenizer
from nltk.tokenize import sent_tokenize
text = "Hello! How are you? I am fine. Great!"
sentences = sent_tokenize(text)
for sentence in sentences:
    print(sentence)