Count the total number of words in a sentence in Python

In this post, we will learn to count the total number of words in a sentence in Python. For this, we will use different inbuilt Python functions.

So welcome back guys in this tutorial where we will count the total number of words present in a sentence.

Python program: Count the total number of words in a sentence

Our first approach will be using the split() function to separate the words with the provided delimiter. In most cases, “space” is used to separate the words in a sentence. So we will pass the ” ” in split() function to separate the words. Let’s see with an example:

string="Codespeedy Technology Pvt Ltd" result=string.split(" ")
count=0
for item in result:
    count+=1
print(f"Total {count} words found)

Output:

Total 4 words found

After splitting words comes in list form. So we can directly use the len()method.

string="Codespeedy Technology Pvt Ltd"
result=string.split(" ")
count=0
count=len(result)
print(count)

Output:

4

But when we have special characters combined with words then these above methods will not work. Let’s see:

string="Codespeedy Technology[Pvt Ltd]. Best Programming content/article"
result=string.split(" ")
count=0
print(result)
for item in result:
    count+=1
print(f"Total {count} found")

#Using the len() method

count=len(result)
print(count)

Output:

['Codespeedy', 'Technology[Pvt', 'Ltd].', 'Best', 'Programming', 'content/article']
Total 6 found
6

To overcome this we will replace all the special characters in sentence with whitespace(” “).

string="Codespeedy Technology[Pvt Ltd]. Best Programming content/article"
spclchar=['[',']','{','}','/','&','#','$','(',')','.']#And many more

#replace special character with space
for i in spclchar:
    string=string.replace(i," ")

result=string.split()
count=0
print(result)
for item in result:
    count+=1
print(f"Total {count} found")
#using the len() method
count=len(result)
print(count)

Output:

['Codespeedy', 'Technology', 'Pvt', 'Ltd', 'Best', 'Programming', 'content', 'article']
Total 8 found
8

I hope you have understood how to count the total number of words in a sentence in Python. If you have any doubts related to this post please comment below.

Also read: How to call an external command from Python

Leave a Reply

Your email address will not be published. Required fields are marked *