We’ll count the occurrence of every word using a dictionary
Every Word
Count the occurrence of every word in our string using a dictionary
# Count words in a String using Dictionary# Define the functiondef freq(string):#step1: A list variable is declared and initialized to an empty list. words = []#step2: Break the string into list of words words = string.split() # or string.lower().split()#step3: Declare a dictionary Dict = {}#step4: Use for loop to iterate words and values to the dictionaryfor key in words: Dict[key] = words.count(key)#step5: Print the dictionaryprint("The Frequency of words is:",Dict)# Call the function and pass string in itfreq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \Everywhere that Mary went The lamb was sure to go")
Count the occurrence one one key/word passed as argument we just edit the above code block slightly to
include the passed key as argument and test for it conditionally
# Count the occurrence of one key/word in a String using Dictionary# Define the functiondef freq(string,passed_key):#step1: A list variable is declared and initialized to an empty list. words = []#step2: Break the string into list of words words = string.split() # or string.lower().split()#step3: Declare a dictionary Dict = {}#step4: Use for loop to iterate words and values to the dictionaryfor key in words:if key == passed_key: # count the occurrence only if condition is True Dict[key] = words.count(key)#step5: Print the dictionary#print(f"{passed_key} Occurs: ",Dict," times")# The above prints out: little Occurs: {'little': 3} times# Let's just print out the count of occurrence without the dictionaryprint(f"{passed_key} Occurs: ",Dict[passed_key]," times")# Call the function and pass string in itfreq("Mary had a little lamb Little lamb, little lamb Mary had a little lamb.Its fleece was white as snow And everywhere that Mary went Mary went, Mary went \Everywhere that Mary went The lamb was sure to go","little")