12-14-2022, 01:24 PM
Python | Split Text into Sentences
Rate this post
Summary: There are four different ways to split a text into sentences:
Using module
Using
Using
Using
[b]Minimal Example[/b]
Problem Formulation
Problem: Given a string/text containing numerous sentences; How will you split the string into sentences?
Example: Let’s visualize the problem with the help of an example.
Method 1: [b]Using nltk.tokenize[/b]
Natural Language Processing (NLP) has a process known as tokenization using which a large quantity of text can be divided into smaller parts called tokens. The Natural Language toolkit contains a very important module known as NLTK tokenize sentence which further comprises sub-modules. We can use this module and split a given text into sentences.
Code:
Explanation:
Caution: You might get an error after installing the package. So, here’s the entire process to install in your system.
Then go ahead and type the following in your Python shell:
That’s it! You are now ready to use the module in your code.
Method 2: [b]Using re.split[/b]
The method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, results in the list of strings .
Approach: Split the given string using alphanumeric separators, and use the either-or metacharacter. It allows you to specify each separator within the expression like so: . Thus, whenever the script encounters any of the mentioned characters specified within the pattern, it will split the given string. The expression ignores all the empty characters.
Code:
Recommended Read: Python Regex Split
Method 3: [b]Using findall[/b]
The method scans the string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order when scanning the string from left to right.
Code:
Explanation: In the expression, i.e.,, all occurrences of characters are grouped except the punctuation marks. denotes that all occurrences of one or more characters except (given by ) ‘’, ‘’, and ‘’ will be returned. Thus, whenever the script finds and groups all characters until any of the mentioned characters within the square brackets are found. As soon as one of the mentioned characters is found it splits the string and finds the next group of characters.
Related Read: Python re.findall() – Everything You Need to Know
Method 4: [b]Using replace[/b]
Approach: The idea here is to replace all the punctuation marks ( and ) present in the given string with a comma () and then split the modified string to get the list of split substrings. The problem here is the last element returned will be an empty string. You can use the method to remove the last element out of the list of substrings (the empty string).
Code:
Related Read: Python String replace()
Conclusion
We have successfully solved the given problem using different approaches. I hope this article helped you in your Python coding journey. Please subscribe and stay tuned for more interesting articles.
Happy coding!![[Image: 1f40d.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png)
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
Rate this post
Summary: There are four different ways to split a text into sentences:
Using Code:
nltk
Using Code:
re.split()
Using Code:
re.findall()
Using Code:
replace[b]Minimal Example[/b]
Code:
text = "God is Great! I won a lottery." # Method 1
from nltk.tokenize import sent_tokenize
print(sent_tokenize(text)) # Method 2
import re
res = [x for x in re.split("[//.|//!|//?]", text) if x!=""]
print(res) # Method 3
res = re.findall(r"[^.!?]+", text)
print(res) # Method 4
def splitter(txt, delim): for i in txt: if i in delim: txt = txt.replace(i, ',') res = txt.split(',') res.pop() return res sep = ['.', '!']
print(splitter(text, sep)) # Output: ['God is Great', ' I won a lottery']Problem Formulation
Problem: Given a string/text containing numerous sentences; How will you split the string into sentences?
Example: Let’s visualize the problem with the help of an example.
Code:
# Input
text = "This is sentence 1. This is sentence 2! This is sentence 3?"
# output
['This is sentence 1', ' This is sentence 2', ' This is sentence 3']Natural Language Processing (NLP) has a process known as tokenization using which a large quantity of text can be divided into smaller parts called tokens. The Natural Language toolkit contains a very important module known as NLTK tokenize sentence which further comprises sub-modules. We can use this module and split a given text into sentences.
Code:
Code:
from nltk.tokenize import sent_tokenize
text = "This is sentence 1. This is sentence 2! This is sentence 3?"
print(sent_tokenize(text)) # ['This is sentence 1.', ' This is sentence 2!', ' This is sentence 3?']Explanation:
- Import the module.Code:
sent_tokenize
- Further, the module allows you to parse the given sentences and break them into individual sentences at the occurrence of punctuations like periods, exclamation, question marks, etc.Code:
sentence_tokenizer
Caution: You might get an error after installing the
Code:
nltkCode:
nltkCode:
Install nltk using → pip install nltkThen go ahead and type the following in your Python shell:
Code:
import nltk
nltk.download('punkt')That’s it! You are now ready to use the
Code:
sentence_tokenizerMethod 2: [b]Using re.split[/b]
The
Code:
re.split(pattern, string)Code:
re.split('a', 'bbabbbab')Code:
['bb', 'bbb', 'b']Approach: Split the given string using alphanumeric separators, and use the either-or
Code:
(|)Code:
re.split("[//.|//!|//?]", text)Code:
x!=""Code:
Code:
import re
text = "This is sentence 1. This is sentence 2! This is sentence 3?"
res = [x for x in re.split("[//.|//!|//?]", text) if x!=""]
print(res) # ['This is sentence 1', ' This is sentence 2', ' This is sentence 3']
Recommended Read: Python Regex SplitMethod 3: [b]Using findall[/b]
The
Code:
re.findall(pattern, string)Code:
Code:
import re
text = "This is sentence 1. This is sentence 2! This is sentence 3?"
res = re.findall(r"[^.!?]+", text)
print(res) # ['This is sentence 1', ' This is sentence 2', ' This is sentence 3']Explanation: In the expression, i.e.,
Code:
re.findall(r"[^.!?]+", text)Code:
[]+Code:
^Code:
!Code:
?Code:
.
Related Read: Python re.findall() – Everything You Need to KnowMethod 4: [b]Using replace[/b]
Approach: The idea here is to replace all the punctuation marks (
Code:
‘!’, ‘?’,Code:
‘.’Code:
,Code:
pop()Code:
Code:
def splitter(txt, delim): for i in txt: if i in delim: txt = txt.replace(i, ',') res = txt.split(',') res.pop() return res sep = ['.', '!', '?']
text = "This is sentence 1. This is sentence 2! This is sentence 3?"
print(splitter(text, sep)) # ['This is sentence 1', ' This is sentence 2', ' This is sentence 3']
Related Read: Python String replace()Conclusion
We have successfully solved the given problem using different approaches. I hope this article helped you in your Python coding journey. Please subscribe and stay tuned for more interesting articles.
Happy coding!
![[Image: 1f40d.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f40d.png)
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

