cryptanalysis/ic.py
2023-09-27 12:30:23 +02:00

43 lines
1012 B
Python

# coding: utf-8
from argparse import ArgumentParser
from functions import readFile, countLetters
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
for i in range(0, len(counts)):
sum = (counts[i] * (counts[i] - 1))
ic += sum / (totalLetters * (totalLetters - 1))
print(f"Index of coincidence: {ic}")
if __name__ == "__main__":
main()