forked from alessandrodd/api_key_detector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentropy.py
executable file
·48 lines (38 loc) · 1.52 KB
/
entropy.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
import math
import sys
def shannon_entropy(item, itemset):
"""
Calculates the [String] Shannon Entropy of an item
:param item: the item [string] of which should be computed the entropy
:param itemset: an iterable representing the item set [charset as a string]
:return: the item's entropy
:rtype: float
"""
if not item:
return 0
entropy = 0.0
for x in itemset:
p_x = float(item.count(x)) / len(item)
if p_x > 0:
entropy = entropy + (p_x * math.log(p_x, 2))
return -entropy
def normalized_entropy(item, itemset, charset_normalization=False):
"""
Calculates the [String] Shannon Entropy relative to the specific item length and set [charset]
(i.e. weighted by the itemset's [charset's] complexity), if charset_normalization is True
:param item: the item [string] of which should be computed the entropy
:param itemset: an iterable representing the item set [charset as a string]
:param charset_normalization: if True, normalize entropy with respect to the item length AND length of the charset
:return: normalized entropy
:rtype: float
"""
if charset_normalization:
return shannon_entropy(item, itemset) / (len(item) * len(itemset))
return shannon_entropy(item, itemset) / len(item)
def main(argv):
if len(argv) != 3:
print("Usage: python {0} \"string to be classified\" charset".format(argv[0]))
return
print(shannon_entropy(argv[1], argv[2]))
if __name__ == '__main__':
main(sys.argv)