【问题标题】:Pretty-printing data from counter - Python来自计数器的漂亮打印数据 - Python
【发布时间】:2013-11-19 21:47:08
【问题描述】:

我对 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,但我并不真正了解如何将其合并到我现有的代码中。

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

【问题讨论】:

  • 您希望pprint 在这里为您做什么?它所做的只是调整大型收藏品的打印方式;您根本没有尝试显示集合。

标签: python collections counter pprint


【解决方案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))

【讨论】:

  • 元音和缺点部分是我已经完成的不同代码的一部分。我只是提供了一个我希望它看起来像的示例。
【解决方案2】:

我不确定这是否是您想要的,但这会打印最常见的字符,然后是出现次数:

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

【讨论】:

  • 这正是我想要的。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-06-22
  • 1970-01-01
  • 2021-03-06
  • 1970-01-01
  • 1970-01-01
  • 2014-05-12
  • 1970-01-01
相关资源
最近更新 更多