top of page
learn_data_science.jpg

Data Scientist Program

 

Free Online Data Science Training for Complete Beginners.
 


No prior coding knowledge required!

How can I count the number of character occurrence in a sentence

In this blog, I would explain how I create a function to count the number of occurrences of a given character in a given word, phrase, or sentence.

And also create a function to count the number of occurrences of a given word in a given phrase or a sentence.


Count the occurrence of a char

# A function to count the occurrence of a char in a word or a sentence def countOccChar(sent, char): sent = sent.lower() #turn the sentence to lower case char = char.lower() #turn the char to lower case count = 0 #A counter to count the occurrence of the character for c in sent : #loop over the sentence if c == char: #Check if the char is the same as the iterator count +=1 #Count the occurrence return(count)




Count the occurrence of a word # A function to count the occurrence of a word in a sentence def countOccWord(sent, word): sent = sent.lower() #turn the sentence to lower case word = word.lower() #turn the word to lower case count = 0 #A counter to count the occurrence of the character #Remove punctuations from the sentence punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' no_punct = "" s = sent.split(" ") #Split the sentence by space for char in sent: #loop over the sentence if char not in punctuations: #To remove the punctuations no_punct = no_punct + char s = no_punct.split(" ") lensent = len(s) #get the length of a sentence for c in range(0,lensent) : if word == s[c]: count +=1 #Count the occurrence of a word return(count)

Check the code from here: geehaad


0 comments

Recent Posts

See All

Commentaires


bottom of page