从我的输出中删除空格并以百分比打印结果

def check_letter_frequency():

        fhand = open('phil.txt')

        letter_frequency_dict = dict()

        for wordz in fhand:

            wordz = wordz.lower()

            words = wordz.strip()


            for letter in words:

                if letter in letter_frequency_dict:

                    letter_frequency_dict[letter] += 1

                else:

                    letter_frequency_dict[letter] = 1

    sorted_letter_frequency = [(key, letter_frequency_dict[key]) for key in sorted(letter_frequency_dict, key=letter_frequency_dict.get, reverse=True)]

        print("letter frequency of:")

        letters = []

        from string import ascii_lowercase

        for key, value in sorted_letter_frequency[:8]:

            # letters.append(ley)

            print('{} : {}'.format(key, value))


    check_letter_frequency()

我的输出如下所示:


letter frequency of: : 182 e : 108 t : 91 o : 77 h : 67 n : 66 i : 64 a : 64 


侃侃无极
浏览 75回答 2
2回答

陪伴而非守候

尝试这个# get the total number, excluding spacestotal = sum([val for key,val in sorted_letter_frequency[:8] if key != ' '])for key, value in sorted_letter_frequency[:8]:    # ignore space again    if key == ' ': continue    # print out frequency as percentage of the total    print('{} : {}%'.format(key, float(value) / total * 100)

狐的传说

如果您只想计算字母,则需要在构建字典时进行检查import stringvalid = string.ascii_letters + string.digitsfor letter in words:    if letter in valid:        if letter in letter_frequency_dict:            letter_frequency_dict[letter] += 1        else:            letter_frequency_dict[letter] = 1至于百分比,您需要获取总字母数并使用它来计算百分比total = sum(letter_frequency_dict.values())for key, value in sorted_letter_frequency[:8]:    print('{} : {}%'.format(key, (float(value) / float(total) * 100.0))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python