When it is required to print all the words occurring in a sentence exactly K times, a method is defined that uses the ‘split’ method, ‘remove’ method and the ‘count’ methods. The method is called by passing the required parameters and output is displayed.
Example
Below is a demonstration of the same
def key_freq_words(my_string, K): my_list = list(my_string.split(" ")) for i in my_list: if my_list.count(i) == K: print(i) my_list.remove(i) my_string = "hi there how are you, how are u" K = 2 print("The string is :") print(my_string) print"The repeated words with frequency", " are :" key_freq_words(my_string, K)
Output
The string is : hi there how are you, how are u The repeated words with frequency 2 are : how are
Explanation
A method named ‘key_freq_words’ is defined that takes a string and a key as parameter.
The string is split based on spaces, and assigned to a list.
This list is iterated over, and if the count of an element is equal to the key values, it is displayed on the console.
Once it has been printed, it is removed from the list.
Outside the method, a string is defined, and is displayed on the console.
The value for key is defined.
The method is called by passing the string and the key.
The output is displayed on the console.