Skip to content

Commit d7747e0

Browse files
committed
Added Word Frequency Counter program in Python
1 parent 3cea941 commit d7747e0

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

strings/word_frequency_counter.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# word_frequency_counter.py
2+
# This program counts the frequency of each word in a paragraph of text.
3+
# Author: jaimin45-art
4+
5+
def word_frequency(text: str):
6+
# Convert to lowercase and remove punctuation
7+
for ch in [',', '.', '?', '!', ';', ':']:
8+
text = text.replace(ch, '')
9+
words = text.lower().split()
10+
11+
freq = {}
12+
for word in words:
13+
freq[word] = freq.get(word, 0) + 1
14+
15+
# Sort by frequency (descending) then alphabetically
16+
sorted_words = sorted(freq.items(), key=lambda x: (-x[1], x[0]))
17+
18+
print("Word Frequency:\n")
19+
for word, count in sorted_words:
20+
print(f"{word} : {count}")
21+
22+
if __name__ == "__main__":
23+
print("Enter a paragraph of text:")
24+
paragraph = input()
25+
word_frequency(paragraph)

0 commit comments

Comments
 (0)