Python Code to Count Word Frequency in Text
Counting how often each word appears is a common job, for example to find the most used words in an article. Python makes it short with collections.Counter.
Count words with Counter
from collections import Counter
text = "to be or not to be that is the question to be"
words = text.split()
counts = Counter(words)
print(counts)
print(counts.most_common(2))
print(counts["be"])
Output:
Tutorials Class - Output Window
Counter({'to': 3, 'be': 3, 'or': 1, 'not': 1, 'that': 1, 'is': 1, 'the': 1, 'question': 1})
[('to', 3), ('be', 3)]
3
The same without Counter
A normal dictionary also works. This is how Counter works inside.
text = "to be or not to be"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
Output:
Tutorials Class - Output Window
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
Note:
Use text.lower() before split() if “The” and “the” should count as the same word. Punctuation should be removed too for real text.
Related: Python Dictionary and Python Strings.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |