0

我对 Python 还很陌生,但仍然无法以我想要的方式显示我拥有的数据。我有这段代码可以确定字符串中最常见的字符。但是,我如何将其打印为:('A', 3).

stringToData = raw_input("Please enter your string: ")
import collections
print (collections.Counter(stringToData).most_common(1)[0])

我只是想深入了解如何将此代码操作为类似于以下内容:

print "In your string, there are: %s vowels and %s consonants." % (vowels, cons)

显然它会说,“在你的字符串中,最常见的字符是 (character),它出现了 (number) 次。”

我正在使用 Python 2.7,我尝试使用,pprint但我并不真正了解如何将其合并到我现有的代码中。

编辑:基本上,我要问的是如何编码查找字符串中最常见的字符并以诸如“在您的字符串中,最常见的字符是(字符)的方式打印它,它出现了(数字)次。 "

4

2 回答 2

4

我不确定这是否是您想要的,但这将打印出现次数最多的字符:

import collections

char, num = collections.Counter(stringToData).most_common(1)[0]
print "In your string, the most frequent character is %s, which occurred %d times" % (char, num)

这将返回最常见字符和出现次数的元组。

collections.Counter(stringToData).most_common(1)[0]
#output: for example: ('f', 5)

例子:

stringToData = "aaa bbb ffffffff eeeee"
char, num = collections.Counter(stringToData).most_common(1)[0]
print "In your string, the most frequent character is %s, which occurred %d times" % (char, num)

输出是:

In your string, the most frequent character is f, which occurred 8 times
于 2013-11-08T00:59:29.497 回答
1

这里真的没什么pprint可做的。该模块是关于自定义打印集合的方式 - 缩进子对象,控制字典键或集合元素的显示顺序等。您根本不尝试打印集合,只是打印一些关于它的信息.

您要做的第一件事是保留集合,而不是为每个打印语句重建它:

counter = collections.Counter(stringToData)

接下来,您必须弄清楚如何从中获取您想要的数据。您已经知道如何找到一对值:

letter, count = counter.most_common(1)[0]

你问的另一件事是元音和辅音的数量。为此,您需要执行以下操作:

all_vowel = set('aeiouyAEIOUY')
all_consonants = set(string.ascii_letters) - all_vowels
vowels = sum(count for letter, count in counter.iteritems()
             if letter in all_vowels)
cons = sum(count for letter, count in counter.iteritems()
           if letter in all_consonants)

现在您只需要使用某种格式将它们打印出来,您已经知道该怎么做:

print "In your string, there are: %s vowels and %s consonants." % (vowels, cons)
print ("In your string, the most frequent character is %s, which occurred %s times."
       % (letter, count))
于 2013-11-08T00:58:55.577 回答