- Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfrequencyanalysis.py
More file actions
Latest commit
executable file
·88 lines (60 loc) · 2.35 KB
/
Copy pathfrequencyanalysis.py
File metadata and controls
executable file
·88 lines (60 loc) · 2.35 KB
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
fromtypingimportDict
fromoperatorimportitemgetter
importjson
defcreate_decryption_dictionary(plaintext_filepath: str, encrypted_filepath: str, dictionary_filepath: str) ->None:
"""
Create an estimated mapping between encrypted letters and
plaintext letters by comparing the frequencies in the
plaintext and encrypted text.
The dictionary is then saved as a JSON file.
"""
sample_plaintext=_readfile(plaintext_filepath)
encrypted_text=_readfile(encrypted_filepath)
sample_plaintext_frequencies=_count_letter_frequencies(sample_plaintext)
encrypted_text_frequencies=_count_letter_frequencies(encrypted_text)
decryption_dict= {}
foriinrange(0, 26):
decryption_dict[encrypted_text_frequencies[i][0]] =sample_plaintext_frequencies[i][0].lower()
f=open(dictionary_filepath, "w")
json.dump(decryption_dict, f)
f.close()
defdecrypt_file(encrypted_filepath: str, decrypted_filepath: str, dictionary_filepath: str) ->None:
"""
Use the dictionary to decrypt the encrypted file
and save the result.
"""
encrypted_text=_readfile(encrypted_filepath)
f=open(dictionary_filepath, "r")
decryption_dict=json.load(f)
f.close()
decrypted_list= []
forletterinencrypted_text:
asciicode=ord(letter.upper())
ifasciicode>=65andasciicode<=90:
decrypted_list.append(decryption_dict[letter])
decrypted_text="".join(decrypted_list)
f=open(decrypted_filepath, "w")
f.write(decrypted_text)
f.close()
def_count_letter_frequencies(text: str) ->Dict:
"""
Create a dictionary of letters A-Z and count the frequency
of each in the supplied text.
Lower case letters are converted to upper case.
All other characters are ignored.
The returned data structure is a list as we need to sort it by frequency.
"""
frequencies= {}
forasciicodeinrange(65, 91):
frequencies[chr(asciicode)] =0
forletterintext:
asciicode=ord(letter.upper())
ifasciicode>=65andasciicode<=90:
frequencies[chr(asciicode)] +=1
sorted_by_frequency=sorted(frequencies.items(), key=itemgetter(1), reverse=True)
returnsorted_by_frequency
def_readfile(path: str) ->str:
f=open(path, "r")
text=f.read()
f.close()
returntext