-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword_analyzer.py
More file actions
43 lines (33 loc) · 1.38 KB
/
Copy pathword_analyzer.py
File metadata and controls
43 lines (33 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Importing required module
from collections import Counter # A built-in Python module for counting hashable items
# Sample paragraph (you can change this or accept user input)
text = input("Enter a paragraph: ")
# 1. Clean and split the text into words
words = text.lower().replace('.', '').replace('!', '').split()
# 2. Use a set to get all unique words
unique_words = set(words)
# 3. Use a dictionary to count word frequencies
word_count = {} # Dictionary to store word: frequency
# 4. Use a for loop to count each word
for word in words:
if word in word_count:
word_count[word] += 1 # Increment count if word exists
else:
word_count[word] = 1 # Add word with count 1
# 5. Use built-in len() function to get total and unique words
total_words = len(words)
unique_word_count = len(unique_words)
# 6. Use sorted() built-in to show top words by frequency
sorted_words = sorted(word_count.items(), key=lambda item: item[1], reverse=True)
# 7. Use Counter from collections as another way to do word counting
counter = Counter(words)
# === OUTPUT SECTION ===
print("🔍 Word Analyzer Results")
print("----------------------------")
print("Total words:", total_words)
print("Unique words:", unique_word_count)
print("Word frequencies (manual method):")
for word, count in sorted_words:
print(f"{word}: {count}")
print("\nWord frequencies (using Counter):")
print(counter)