count words in string python code example

Example 1: Python Program to Count the Occurrences of a Word in a Text File

#get file object reference to the file
file = open("C:\workspace\python\data.txt", "r")
#read content of file to string
data = file.read()
#get number of occurrences of the substring in the string
occurrences = data.count("python")
print('Number of occurrences of the word :', occurrences)

Example 2: how to count the occurrence of a word in string python

# define string
string = "Python is awesome, isn't it?"
substring = "is"

count = string.count(substring)

# print count
print("The count is:", count)

Example 3: count words in string python

import string 

# sentence = ""
sentence = str(input("Enter here: "))

# Remove all punctuations
sentence = sentence.translate(str.maketrans('', '', string.punctuation))

# Remove all numbers"
sentence = ''.join([Word for Word in sentence if not Word.isdigit()])

count = 0;

for index in range(len(sentence)-1) :
    if sentence[index+1].isspace() and not sentence[index].isspace():
        count += 1 
        
print(count)

Tags:

Java Example