main.py 721 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from math import log
  2. charCount = {}
  3. numberOfBits = 0
  4. def count(line):
  5. global numberOfBits
  6. for c in line:
  7. # Size increases
  8. numberOfBits += 1
  9. # Count
  10. if c in charCount:
  11. charCount[c] += 1
  12. else:
  13. charCount[c] = 1
  14. with open("Data/hello.txt", 'rb') as f :
  15. print("Reading file")
  16. for l in f:
  17. count(l)
  18. print("The map :")
  19. print(charCount)
  20. print("Number of characters :")
  21. print(len(charCount))
  22. print("Number of chars :")
  23. print(numberOfBits)
  24. print("Computing entropy")
  25. entropy = 0.0
  26. for key in charCount:
  27. f = charCount[key] / numberOfBits
  28. entropy -= f * log(f, 2)
  29. print(entropy)