Count number of sentences in a string in Python
Hello friends, sometimes you may have a long text to read and count the number of sentences in that text. Instead of counting the full stops all by yourself, you can write a simple piece of code in Python. In this tutorial, I will tell you how you can count the number of sentences in a string.
Count the number of sentences in a string
I have used two methods to perform this task.
- without predefined function
- with predefined function
Without predefined function
I have taken a multiline string, for example, stored in a temporary variable, string
. I have then initialized two empty lists as string_list
and l
respectively. Now to iterate every character of the string I have run a for loop with 0 as its starting value and the length of the string as its end value.
Code :
string = '''This is CodeSpeedy Technologies Pvt Ltd. We are software development & app development company. We can turn your idea into digital reality. We provide digital and tech solutions for businesses. Our team is always committed to fulfill your requirements.''' string_list = [] l = [] for i in range(0, len(string)): if string[i] != ".": string_list.append(string[i]) elif string[i] == "." and string[i+1].isspace(): l.append(string_list) string_list = [] print(len(l))
Check if the string character at the ith position is not a full stop. If yes, append the iterated character of the string to string_list
. Else, append the string_list
to the list, l. After the for loop ends, I have printed the length of the list, l
using the len() function.
Output :
5
With predefined function
You can count the number of sentences in a string, by using two functions split()
and len()
. I have used the split()
function by passing a full stop as an argument, this acts as a separator between two sentences. split()
function returns a list of all the sentences separated by a full stop. However, it also considers a whitespace beyond the last full top. This is why while printing the length of the list, string_list
using the len() function I have subtracted 1 from it.
Code :
string_list = string.split(".") print(len(string_list)-1)
However, the split()
function will consider any other full stop between the sentences, for example, ‘Mr.’ .
Output :
5
Now you can count the number of sentences present in the string using Python.
Leave a Reply