Advertisement
1nikitas

Untitled

Oct 25th, 2021
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. from __future__ import division
  2.  
  3. inputFileName = 'gb.txt'
  4.  
  5. def readfile(fname):
  6. f = open(fname, 'r')
  7. s = f.read()
  8. f.close()
  9. return s.lower()
  10.  
  11. def countChars(t):
  12. charDict = {}
  13. for char in t:
  14. if char in charDict: charDict[char] += 1
  15. else: charDict[char] = 1
  16. return charDict
  17.  
  18. def findMostCommon(charDict):
  19. mostFreq = ''
  20. mostFreqCount = 0
  21. for k in charDict:
  22. if charDict[k] > mostFreqCount:
  23. mostFreqCount = charDict[k]
  24. mostFreq = k
  25. return mostFreq
  26.  
  27. def printCounts(charDict):
  28. for k in charDict:
  29. #First, handle some chars that don't show up very well when they print
  30. if k == '\n': print '\\n', charDict[k] #newline
  31. elif k == ' ': print 'space', charDict[k]
  32. elif k == '\t': print '\\t', charDict[k] #tab
  33. else: print k, charDict[k] #Normal character - print it with its count
  34.  
  35. def printAlphabetically(charDict):
  36. keyList = charDict.keys()
  37. keyList.sort()
  38. for k in keyList:
  39. #First, handle some chars that don't show up very well when they print
  40. if k == '\n': print '\\n', charDict[k] #newline
  41. elif k == ' ': print 'space', charDict[k]
  42. elif k == '\t': print '\\t', charDict[k] #tab
  43. else: print k, charDict[k] #Normal character - print it with its count
  44.  
  45. def printByFreq(charDict):
  46. aList = []
  47. for k in charDict:
  48. aList.append([charDict[k], k])
  49. aList.sort() #Sort into ascending order
  50. aList.reverse() #Put in descending order
  51. for item in aList:
  52. #First, handle some chars that don't show up very well when they print
  53. if item[1] == '\n': print '\\n', item[0] #newline
  54. elif item[1] == ' ': print 'space', item[0]
  55. elif item[1] == '\t': print '\\t', item[0] #tab
  56. else: print item[1], item[0] #Normal character - print it with its count
  57.  
  58. def main():
  59. text = readfile(inputFileName)
  60. charCounts = countChars(text)
  61. mostCommon = findMostCommon(charCounts)
  62. #print mostCommon + ':', charCounts[mostCommon]
  63. #printCounts(charCounts)
  64. #printAlphabetically(charCounts)
  65. printByFreq(charCounts)
  66.  
  67. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement