Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9054cb7

Browse files
author
Amogh Singhal
authored
Create topThreeFrequent.py
1 parent 07fc6d4 commit 9054cb7

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

‎bits_wilp/topThreeFrequent.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
filepath = './sample.txt'
2+
freq_counter = {}
3+
4+
# using context manager
5+
with open(filepath, mode='r') as handle:
6+
content = handle.read()
7+
words = content.split()
8+
# file is closed now
9+
10+
for w in words:
11+
if w not in freq_counter.keys():
12+
freq_counter[w] = 1
13+
else:
14+
freq_counter[w] += 1
15+
16+
# sorting the sequence by values in `reverse` order
17+
sorted_by_freq = sorted(freq_counter, key=freq_counter.get, reverse=True)
18+
19+
top_three = sorted_by_freq[:3]
20+
for k in top_three:
21+
print(k, ":", freq_counter[k])

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /