In: Computer Science
Write a function in Python to take in a piece of sample text via a long string (you pick the string) and to output a dictionary with each word as a key and it’s frequency (the number of times it occurred in the original string) as the value. Show an example of your function in use. Be sure to strip out any punctuation.
Solution : The code works totally fine with large strings as well. I have checked it.
import re #importing regular expression module
test_string='''Nory was a Catholic because her mother was a Catholic, and the mother was a Catholic because her father was a Catholic, and her father was a Catholic because his mother was a Catholic, or had been. '''
res = re.findall(r'\w+', test_string) #extracting words from string and also it ignores the punctuations
frequency = {} #empty dictionary
for item in res: #looping through list 'res' and creating the required dictionary
if (item in frequency):
frequency[item]+=1
else:
frequency[item]=1
print("The required dictionary content :-\n")
for key, value in frequency.items(): #loop to print the value and key from the dictionary
print ("% s : % d"%(key, value))
Output :