-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathngram_score.py
50 lines (40 loc) · 1.34 KB
/
ngram_score.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
"""
fitness_score of text using n-gram statistics (probabilities)
Used quadgram corpus from Practical Cryptography website by James Lyons which is cited below
Date: 29th Nov. 2018
"""
from math import log10
class ngram_score(object):
def __init__(self, ngramfile, sep=' '):
"""
load a file containing ngrams and counts, calculate log probabilities
"""
self.ngrams = {}
for line in open(ngramfile):
key,count = line.split(sep)
self.ngrams[key] = int(count)
self.L = len(key)
self.N = sum(self.ngrams.values())
# calculate log probabilities
for key in self.ngrams.keys():
self.ngrams[key] = log10(float(self.ngrams[key])/self.N)
self.floor = log10(0.01/self.N)
def score(self, text):
"""
compute the score of text
"""
score = 0
ngrams = self.ngrams.__getitem__
for i in range(len(text) - self.L + 1):
if text[i:i+self.L] in self.ngrams:
score += ngrams(text[i:i+self.L])
else:
score += self.floor
return score
"""
Citation:
Title: Quadgram Statistics as a Fitness Measure
Author: James Lyons
Date: 2009-2012
Availability: http://practicalcryptography.com
"""