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

Writer: Gehad HishamGehad Hisham

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


 
 

Comments


COURSES, PROGRAMS & CERTIFICATIONS

 

Advanced Business Analytics Specialization

Applied Data Science with Python (University of Michigan)

Data Analyst Professional Certificate (IBM)

Data Science Professional Certificate (IBM)

Data Science Specialization (John Hopkins University)

Data Science with Python Certification Training 

Data Scientist Career Path

Data Scientist Nano Degree Program

Data Scientist Program

Deep Learning Specialization

Machine Learning Course (Andrew Ng @ Stanford)

Machine Learning, Data Science and Deep Learning

Machine Learning Specialization (University of Washington)

Master Python for Data Science

Mathematics for Machine Learning (Imperial College London)

Programming with Python

Python for Everybody Specialization (University of Michigan)

Python Machine Learning Certification Training

Reinforcement Learning Specialization (University of Alberta)

Join our mailing list

Data Insight participates in affiliate programs and may sometimes get a commission through purchases made through our links without any additional cost to our visitors.

bottom of page