- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print all words occurring in a sentence exactly K times
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.
- Related Articles
- Reverse all the words of sentence JavaScript
- Python - Generate all possible permutations of words in a Sentence
- C# program to remove all duplicates words from a given sentence
- Java program to remove all duplicates words from a given sentence
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Print all funny words in a string in C++
- Count substrings with each character occurring at most k times in C++
- Rearrange Words in a Sentence in C++
- Count words in a sentence in Python program
- Count palindrome words in a sentence in C++
- Python program to count words in a sentence
- Program to find number of sublists that contains exactly k different words in Python
- Count of Numbers in a Range where digit d occurs exactly K times in C++
- Counting number of words in a sentence in JavaScript
- Print all possible words from phone digits in C++
