Advertisement
Guest User

New_2

a guest
Mar 29th, 2017
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.47 KB | None | 0 0
  1. #вероятностные методы в криптологии
  2.  
  3. import math
  4.  
  5. '''
  6. ####текст только буквы без пробелов
  7. text = open('text.txt', 'r')
  8. nospacetxt = open('nospacetxt.txt', 'w')
  9.  
  10. for ch in text.read().upper():
  11. if ch.isalpha(): # or ch == ' ':
  12. nospacetxt.write(ch)
  13.  
  14. text.close()
  15. nospacetxt.close()'''
  16.  
  17. ############делю текст на н-граммы
  18. L = [] #список н-грамм
  19. nospacetext_f = open('nospacetext.txt', 'r')
  20. gramms_f = open('gramms.txt', 'w')
  21. S = nospacetext_f.read()
  22.  
  23. for j in range(1, 13):
  24. for i in range(len(S)+1-j):
  25. gram = S[i:i+j:]
  26. L.append(gram)
  27. gramms_f.write(gram + ', ')
  28.  
  29. nospacetext_f.close()
  30. gramms_f.close()
  31.  
  32. gramunic_f = open('gramunic.txt', 'w')
  33. gramunic = []
  34.  
  35.  
  36. '''for gram in L:
  37. if gram not in gramunic:
  38. gramunic.append(gram)
  39. gramunic_f.write(gram + ', ')
  40. gramunic_f.close()'''
  41.  
  42. gramunic = list(set(L))
  43.  
  44. ########подсчет каждой н-граммы
  45. gramstat = {}
  46.  
  47. ngramstat_f = open('ngramstat.txt', 'w')
  48. for gram in gramunic:
  49. gramunic_f.write(gram + ', ')
  50. gramstat[gram] = S.count(gram)
  51. ngramstat_f.write(gram + ' : ' + str(gramstat[gram]) + '\n')
  52.  
  53. ngramstat_f.close()
  54.  
  55. ########подсчет кол-ва всех н-грамм
  56. counts = [0]*12
  57. for gram in L:
  58. counts[len(gram)-1] += 1
  59. print('Общее кол-во н-грамм: ',counts)
  60.  
  61. #########подсчет кол-ва уникальных н-грамм
  62. countunic = [0]*12
  63. for gram in gramunic:
  64. countunic[len(gram)-1] += 1
  65. #print(countunic)
  66.  
  67. #########вероятность какой-то н-граммы
  68. gramver = {}
  69.  
  70. gramver_f = open('gramver_f.txt', 'w')
  71. for gram in gramstat:
  72. gramver[gram] = gramstat[gram]/counts[len(gram)-1] #ну тут вероятность p считаем каждой н-граммы,
  73. gramver_f.write(gram + ' : ' + str('%.10f'%gramver[gram]) + '\n')
  74. gramver_f.close()
  75.  
  76. ##########ДЛЯ КАЖДОЙ Н-ГРАММЫ Нs
  77. H = []
  78. Hs = []
  79.  
  80. for k in range(1,13):
  81. for gram in gramver:
  82. if len(gram) == k:
  83. Hgram = gramver[gram]*math.log(gramver[gram], 2)#(промежуточный результат)тут энтропию H для каждых н-грамм считаем
  84. H.append(Hgram)
  85. # print(H)
  86. Hs.append(-sum(H))
  87.  
  88. H.clear()
  89. print('Hs ', Hs)
  90.  
  91.  
  92. HL = Hs[11]/12 #тут типо предел находим, получаем Hl
  93. print('Hl ', HL)
  94. R = 1 - HL/math.log(26, 2) #КАКОЕ БЕРЕМ n ??????????? #это избыточность
  95. print('R ', R)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement