Welcome, guest | Sign In | My Account | Store | Cart

Calculates the frequency of characters within a block of text. In the context of cryptography, these values can be compared to a frequency table in order to attempt to ascertain the original message.

Python, 26 lines
 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
def frequency_analysis(text):
    '''Counts the frequency of characters within a text

    text -- the text to be analysed

    '''
    import re
    alphabet = {}
    for i in range(26):
        alphabet[chr(65+i)] = 0
    for char in text.upper():
        for i in range(94):
            if chr(33 + i) == char:
                try:
                    alphabet[char] += 1
                except KeyError:
                    alphabet[char] = 1
                break
    re.sub(r'\s', '', text)
    count = len(text)
    for i in range(94):
        char = chr(33+i)
        try:
            print("{} = {}%".format(char, round(alphabet[char] * 100/count, 1)))
        except KeyError:
            pass