54 lines
1.3 KiB
Python
54 lines
1.3 KiB
Python
# coding: utf-8
|
|
|
|
from argparse import ArgumentParser
|
|
from functions import readFile, countLetters
|
|
import matplotlib.pyplot as plt
|
|
|
|
|
|
def checkArguments():
|
|
args = ArgumentParser(description='Cryptanalyst')
|
|
args.add_argument('-f', '--filename', help='Text to analyze')
|
|
return args.parse_args()
|
|
|
|
def main():
|
|
args = checkArguments()
|
|
|
|
# Read file
|
|
dataFile = readFile(args.filename)
|
|
|
|
# Get number of letters
|
|
totalLetters = countLetters(dataFile)
|
|
|
|
counts = []
|
|
|
|
for i in range (0, 26):
|
|
counts.append(0)
|
|
|
|
# Count the number of letter in our text
|
|
letterToAscii = ord('a') # Get the ASCII code
|
|
for i in dataFile:
|
|
l = ord(i) - letterToAscii
|
|
if l >= 0 and l <= 26:
|
|
counts[l] += 1
|
|
|
|
# We calculate the sum of all character in the text
|
|
ic = 0
|
|
allIC = list()
|
|
for i in range(0, len(counts)):
|
|
sum = (counts[i] * (counts[i] - 1))
|
|
currentIC = sum / (totalLetters * (totalLetters - 1))
|
|
allIC.append(currentIC)
|
|
ic += currentIC
|
|
print(f"Index of coincidence: {ic}")
|
|
|
|
largeur = 0.5
|
|
y = list()
|
|
for alphabet in range(0, 26):
|
|
y.append(chr(ord('a') + alphabet))
|
|
plt.bar(y, allIC, largeur)
|
|
plt.show()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|