Untitled


SUBMITTED BY: Guest

DATE: Nov. 2, 2013, 9:59 p.m.

FORMAT: Python

SIZE: 1.2 kB

HITS: 945

  1. tm = open('pg35.txt','r')
  2. dict = {}
  3. arr_v = []
  4. arr_k = []
  5. placeholder = None
  6. itera = True
  7. # split all text in the book in words and save the count of same word
  8. for line in tm:
  9. line = line.strip()
  10. line = line.translate(None,'!@#$%^&*()_+`~{}[\\]:"|\';<>?/.,<>-=')
  11. line = line.lower()
  12. list = line.split(' ')
  13. for word in list:
  14. if word in dict:
  15. count = dict[word]
  16. count += 1
  17. dict[word] = count
  18. else:
  19. dict[word] = 1
  20. # assing dictonary to array for sort
  21. for word,count in dict.iteritems():
  22. arr_v.append(count)
  23. arr_k.append(word)
  24. # dictionary sort desc
  25. while itera:
  26. itera = False
  27. for item in range(0,len(arr_v)-1):
  28. if arr_v[item] < arr_v[item+1]:
  29. itera = True
  30. placeholder=arr_v[item+1]
  31. arr_v[item+1]=arr_v[item]
  32. arr_v[item]=placeholder
  33. placeholder=arr_k[item+1]
  34. arr_k[item+1]=arr_k[item]
  35. arr_k[item]=placeholder
  36. # write ordered result to file
  37. res = open('result.txt','w')
  38. for item in arr_k:
  39. res.write("The word \"" + item + "\" is present " + str(dict[item]) + " times. \n")
  40. res.close()

comments powered by Disqus