Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #вероятностные методы в криптологии
- import math
- '''
- ####текст только буквы без пробелов
- text = open('text.txt', 'r')
- nospacetxt = open('nospacetxt.txt', 'w')
- for ch in text.read().upper():
- if ch.isalpha(): # or ch == ' ':
- nospacetxt.write(ch)
- text.close()
- nospacetxt.close()'''
- ############делю текст на н-граммы
- L = [] #список н-грамм
- nospacetext_f = open('nospacetext.txt', 'r')
- gramms_f = open('gramms.txt', 'w')
- S = nospacetext_f.read()
- for j in range(1, 13):
- for i in range(len(S)+1-j):
- gram = S[i:i+j:]
- L.append(gram)
- gramms_f.write(gram + ', ')
- nospacetext_f.close()
- gramms_f.close()
- gramunic_f = open('gramunic.txt', 'w')
- gramunic = []
- '''for gram in L:
- if gram not in gramunic:
- gramunic.append(gram)
- gramunic_f.write(gram + ', ')
- gramunic_f.close()'''
- gramunic = list(set(L))
- ########подсчет каждой н-граммы
- gramstat = {}
- ngramstat_f = open('ngramstat.txt', 'w')
- for gram in gramunic:
- gramunic_f.write(gram + ', ')
- gramstat[gram] = S.count(gram)
- ngramstat_f.write(gram + ' : ' + str(gramstat[gram]) + '\n')
- ngramstat_f.close()
- ########подсчет кол-ва всех н-грамм
- counts = [0]*12
- for gram in L:
- counts[len(gram)-1] += 1
- print('Общее кол-во н-грамм: ',counts)
- #########подсчет кол-ва уникальных н-грамм
- countunic = [0]*12
- for gram in gramunic:
- countunic[len(gram)-1] += 1
- #print(countunic)
- #########вероятность какой-то н-граммы
- gramver = {}
- gramver_f = open('gramver_f.txt', 'w')
- for gram in gramstat:
- gramver[gram] = gramstat[gram]/counts[len(gram)-1] #ну тут вероятность p считаем каждой н-граммы,
- gramver_f.write(gram + ' : ' + str('%.10f'%gramver[gram]) + '\n')
- gramver_f.close()
- ##########ДЛЯ КАЖДОЙ Н-ГРАММЫ Нs
- H = []
- Hs = []
- for k in range(1,13):
- for gram in gramver:
- if len(gram) == k:
- Hgram = gramver[gram]*math.log(gramver[gram], 2)#(промежуточный результат)тут энтропию H для каждых н-грамм считаем
- H.append(Hgram)
- # print(H)
- Hs.append(-sum(H))
- H.clear()
- print('Hs ', Hs)
- HL = Hs[11]/12 #тут типо предел находим, получаем Hl
- print('Hl ', HL)
- R = 1 - HL/math.log(26, 2) #КАКОЕ БЕРЕМ n ??????????? #это избыточность
- print('R ', R)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement