Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program for most frequent word in Strings List
When working with lists of strings, you may need to find the most frequent word across all strings. Python provides several approaches to solve this problem efficiently using collections and built-in functions.
Using defaultdict
The defaultdict from the collections module automatically initializes missing keys with a default value, making word counting straightforward ?
from collections import defaultdict
sentences = ["python is best for coders", "python is fun", "python is easy to learn"]
print("The list is:")
print(sentences)
word_count = defaultdict(int)
for sentence in sentences:
for word in sentence.split():
word_count[word] += 1
most_frequent = max(word_count, key=word_count.get)
print("The word that has the maximum frequency:")
print(most_frequent)
print("Frequency:", word_count[most_frequent])
The list is: ['python is best for coders', 'python is fun', 'python is easy to learn'] The word that has the maximum frequency: python Frequency: 3
Using Counter
The Counter class provides a more direct approach for counting occurrences ?
from collections import Counter
sentences = ["python is best for coders", "python is fun", "python is easy to learn"]
# Combine all words from all sentences
all_words = []
for sentence in sentences:
all_words.extend(sentence.split())
word_counter = Counter(all_words)
most_frequent = word_counter.most_common(1)[0]
print("Most frequent word:", most_frequent[0])
print("Frequency:", most_frequent[1])
Most frequent word: python Frequency: 3
Using Regular Dictionary
You can also use a regular dictionary with manual key checking ?
sentences = ["python is best for coders", "python is fun", "python is easy to learn"]
word_count = {}
for sentence in sentences:
for word in sentence.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
most_frequent = max(word_count, key=word_count.get)
print("Most frequent word:", most_frequent)
print("All word frequencies:", word_count)
Most frequent word: python
All word frequencies: {'python': 3, 'is': 3, 'best': 1, 'for': 1, 'coders': 1, 'fun': 1, 'easy': 1, 'to': 1, 'learn': 1}
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
defaultdict |
High | Good | Simple word counting |
Counter |
Highest | Best | Multiple statistics needed |
| Regular dict | Medium | Good | No imports required |
Conclusion
Use Counter for the most readable and efficient solution when working with word frequencies. The defaultdict approach is also excellent for simple counting tasks without additional statistics.
Advertisements
