brewersfan1976

ch5-ex4.py

Aug 7th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.72 KB | None | 0 0
  1. # program that reads data from a text file
  2. # and counts the frequency of words in the file
  3. # and displays the frequency in descending order
  4.  
  5. from collections import Counter
  6.  
  7. # open file
  8.  
  9. file = open("sample2CAP.txt", "r")
  10.  
  11. # store the file contents in the temp variable
  12.  
  13. temp = file.read()
  14.  
  15. # break data into separate words and store them in a list
  16.  
  17. words = list(temp.split())
  18.  
  19. # count the number of each word in the file
  20.  
  21. words_count = Counter(words)
  22.  
  23. # store the number of words in descending order
  24.  
  25. words_count_descending = words_count.most_common()
  26.  
  27. # create a dictionary
  28.  
  29. d = {}
  30.  
  31. # store the list in a dictionary
  32.  
  33. d = dict(words_count)
  34.  
  35. # print sorted dictionary
  36.  
  37. print words_count_descending
Advertisement
Add Comment
Please, Sign In to add comment