在Python中编辑collections.Counter的输出

时间:2017-09-19 18:41:59

标签: python-2.7 counter

这里有新的Python学习者,我正在试图找出如何根据我的教程规范获得所需的输出格式。基本上我要键入任何字符(例如asjndkfsdhfbhdbhssassasa82),程序是计算前5个最常用的字符。到目前为止,我能够获得所需的结果,但是根据我的实验室规格,我无法打印出来。

目前,我的输出是

(字符):(频率)

(字符):(频率)

如何使其显示为(字符):(频率),(字符):(频率)等?

import sys
import collections

charInput = sys.argv[1].lower()
charInputTemp = list(charInput)    #Convert entire string into individual characters

charInputArray = []

for char in charInput:
    charInputArray.append(char)    #Add each character to array for sorting     

charInputArray.sort()

letters = collections.Counter(charInputArray)     #Get number of occurrence of a character

for letter, count in letters.most_common(5):    #Get 5 most frequent character
    print '%s:%d' % (letter, count)

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

尝试这个

import sys
import collections

charInput = sys.argv[1].lower()
charInputTemp = list(charInput)    #Convert entire string into individual characters

charInputArray = []

for char in charInput:
    charInputArray.append(char)    #Add each character to array for sorting     

charInputArray.sort()

letters = collections.Counter(charInputArray)   #Get number of occurrence of a character

output = []
for letter, count in letters.most_common(5):    #Get 5 most frequent character
    output.append(str(letter)+":"+str(count))
print (",".join(output))