我对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
,但我真的不明白如何将其合并到我现有的代码中。
编辑:基本上,我要问的是如何编码查找字符串中最常见的字符并以“在你的字符串中,最常见的字符是(字符)”的方式打印它发生(次数)。“
答案 0 :(得分: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
答案 1 :(得分:0)
pprint
在这里没有任何帮助。该模块是关于自定义打印集合的方式 - 缩进子对象,控制字典键或设置元素的显示顺序等。您根本不打算打印集合,只需打印一些有关它的信息
您要做的第一件事是保留集合,而不是为每个print语句重建它:
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))