How to find the k most frequent words in a given a list of words with Python

2 Answers

0 votes
from collections import Counter

arr = ["python", "c", "c", "java", "cpp", "c", "python"]
k = 2

frequentWords = Counter(arr)

for index, (key, value) in enumerate(frequentWords.items()):
    print(key, '-', value)
    if (index == k - 1):
        break
    
    

'''
run:

python - 2
c - 3

'''

 

 



answered May 28, 2023 by avibootz
0 votes
from collections import Counter
 
arr = ["python", "c", "c", "java", "cpp", "c", "python"]
k = 2
 
frequentWords = Counter(arr)
 
print(frequentWords.most_common(k))
     
     
 
'''
run:
 
[('c', 3), ('python', 2)]

'''

 



answered May 29, 2023 by avibootz

Related questions

...