198 CHAPTER11. DATA COLLECTIONS
counts = {}
for w in words:
try:
counts[w]= counts[w] + 1
except KeyError:
counts[w]= 1
# output analysisof n most frequent words.
n = input("Outputanalysis of how many words? ")
items = counts.items()
items.sort(compareItems)
for i in range(n):
print "%-10s%5d"% items[i]
if name == ’main’:main()
Justforfun,here’s theresultofrunningthisprogramtofindthetwentymostfrequentwordsinthebook
you’re readingrightnow.
This program analyzesword frequency in a file
and prints a reporton the n most frequent words.
File to analyze: book.txt
Output analysis of howmany words? 20
the 6428
a 2845
of 2622
to 2468
is 1936
that 1332
and 1259
in 1240
we 1030
this 985
for 719
you 702
program 684
be 670
it 618
are 612
as 607
can 583
will 480
an 470
11.7 Exercises
- Giventheinitialstatements
import string
s1 = [2,1,4,3]
s2 = [’c’,’a’,’b’]
show theresultofevaluatingeachofthefollowingsequenceexpressions: