-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathex10_tuple_and_sorting.py
More file actions
37 lines (32 loc) · 1.01 KB
/
ex10_tuple_and_sorting.py
File metadata and controls
37 lines (32 loc) · 1.01 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
name=input('enter file:')
handle=open(name)
# count the word frequencies of the file;
counts=dict()
for line in handle:
words=line.split()
for word in words:
counts[word]=counts.get(word,0)+1
##or we can write our syntax like below:
# if word in counts:
# counts[word]=counts[word]+1
# else:
# counts[word]=1
# figure out the most frequent word:
bigcount=None
bigword=None
for word,count in counts.items():
if bigcount is None or count>bigcount:
bigword=word
bigcount=count
print('the most frequent word is: ',bigword,'the frequency is: ',bigcount)
# create a list containing all the tuples in counts:
lst=list()
for key,val in counts.items():
newtup=(val,key)
lst.append(newtup)
# sorted the list in reverse order:
lst=sorted(lst,reverse=True)
# print out the five most frequent words:
print('the five most frequent words are: ')
for key,val in lst[:5]:
print(key,val)