''' Count the number of times each character appears in the ciphertext file Saves counts into a file named .counts.csv Author: Tim Pierson, Dartmouth CS55, Winter 2021 Usage: python3 counts.py ''' import sys alphabet = 'abcdefghijklmnopqrstuvwxyz' #only consider these characters if __name__ == '__main__': #usage check: make sure we got a filename to read if len(sys.argv) != 2: print("Usage: python3 counts.py ") print("Looks like you did not provide a filename") exit() #read ciphertext file into variable named text f = open(sys.argv[1], "r") text = f.read() f.close() #get unique characters in text (sorted here for debugging) #use a set for efficiency! characters = ''.join(sorted(set(text))) #characters is a string print("Ciphertext is:") print(text) print("\nUnique characters are:") print(characters) #add missing characters from our alphabet so we get a zero count for them for c in alphabet: if not c in characters: characters += c #append character from alphabet not in ciphertext #count how many times each character found in ciphertext counts = {} for c in characters: counts[c] = text.count(c) #print in descending sorted order #also save as csv for later analysis print("Character counts in descending order:") f = open(sys.argv[1]+".counts.csv","w") for key, value in sorted(counts.items(), key=lambda item: item[1], reverse=True): if key in alphabet: #do not include punctuation here print(key,value) f.write(key+","+str(value)+"\n") f.close()