我是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)

显然,它会说:“在您的字符串中,最常见的字符是(字符),是(数字)。”

我正在使用Python 2.7,然后尝试使用 pprint 但是我真的不明白如何将其纳入我的现有代码中。

编辑:基本上,我要问的是如何在字符串中查找最频繁的字符并以“在字符串中,最常见的字符是(字符),发生(数字)次的方式。 “

有帮助吗?

解决方案

我不确定这是否是您想要的,但这会打印出最常见的字符,伴随着事件的数量:

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

其他提示

真的什么都没有 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))
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top