当前位置: 动力学知识库 > 问答 > 编程问答 >

string - Python character frequncy in decending order, if similar based on aphabets

问题描述:

how to order charters of a descending order? if similar apathetically.

frequency first then alphabetical series .

#!/user/bin/python3

# -*- coding: utf-8 -*-

import string

text = """

Mississippi

"""

# create a character: frequency dictionary

charFreqDic = {}

for char in text.upper():

charFreqDic[char] = charFreqDic.get(char, 0) + 1

print ("Characters sorted by ASCII number:")

# create a sorted list of keys

key_list = sorted(charFreqDic.keys())

for key in key_list:

# don't show space and newline

if key not in " \n":

# associate the value with the key

print ("%2s %3d" % (key, charFreqDic[key]))

print ("Characters sorted by frequency:")

print("\n")

print("No Occur"+"\t "+ "Character")

# convert charFreqDic to list of (k, v) tuples with charFreqDic.items()

# flip tuple elements to (v, k) using list comprehension

# then sort list of tuples (order is v,k), highest v first

#dictionary to list

copytolist=[]

for K,V in charFreqDic.items():

copytolist.append((V,K));

copytolist=sorted(copytolist,reverse=True)

print(copytolist)

print("Words sorted by frequency:")

print("\n")

print("No Occur" + "\t " + "Word")

for K in copytolist:

if K[1] not in " \n":

print(str(K[0]) + "\t\t\t " + str(K[1]) + "'s")

output is

Words sorted by frequency:

No Occur Word

4 S's

4 I's

2 P's

1 M's

But I wanted the output to be ordered both based on frequency and based on alphabetical series if frequency is similar.

No Occur Word

4 I's

4 S's

2 P's

1 M's

分享给朋友:
您可能感兴趣的文章:
随机阅读: