美文网首页学习喵喵?
python 分析字母出现频率

python 分析字母出现频率

作者: 王一航 | 来源:发表于2017-04-28 09:25 被阅读150次

    代码 :

    #!/usr/bin/env python
    # coding:utf-8
    
    import string
    
    with open("data.txt", "r") as f:
        data = f.read()
    
    letters = [0 for x in range(0, 26)]
    frequency = "EARIOTNSLCUDPMHGBFYWKVXZJQ".lower()
    
    print frequency
    
    for i in data:
        if i.isalpha():
            i = i.lower()
            index = ord(i) - ord('a')
            letters[index] += 1
    
    temp_letters = [{} for x in range(0, 26)]
    
    counter = 0
    for i in letters:
        temp_letters[counter] = {chr(ord('a') + counter): i}
        counter += 1
    
    
    def compare(a, b):
        return a.values()[0] - b.values()[0]
    
    
    target = ''
    
    
    for i in sorted(temp_letters, compare, None, True):
        target += target.join(i.keys())
    
    
    print "[+] Freque : %s" % frequency
    print "[+] Target : %s" % target
    
    table = string.maketrans(frequency, target)
    
    print data
    print string.translate(data, table)
    
    

    相关文章

      网友评论

        本文标题:python 分析字母出现频率

        本文链接:https://www.haomeiwen.com/subject/oljozttx.html