使用占位符字符串打印字典键值对

时间:2018-03-09 04:59:29

标签: python dictionary printing

我正在尝试编写一个程序,其输出如下所示:

father is repeated 2 times
where is repeated 1 time
art is repeated 1 time
are is repeated 1 time
thou is repeated 1 time

这就是我现在所拥有的:

x = input('Please enter a string: ').lower()
def counter():
    counts = dict()
    words = str.split(x)

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
            print(counts)
    return counts

counter()

打印出来像这样:

   Please enter a string:  father father where art are thou
   {'father': 2, 'where': 1, 'art': 1, 'are': 1, 'thou': 1}

如何以上面显示的格式打印数据?

4 个答案:

答案 0 :(得分:3)

解决原始问题,使用占位符字符串并使用str.format插入值。必须在变量中捕获counter()的返回值,例如counts

placeholder = '{} is repeated {} time{}'

counts = counter()
for k, v in counts.items():
    print(placeholder.format(k, v, 's' if v > 1 else ''))

father is repeated 2 times
where  is repeated 1 time
art    is repeated 1 time
are    is repeated 1 time
thou   is repeated 1 time

(输出实际上并没有像这样对齐,我只是在这里修复它,所以它在我的强迫症上少了。)

作为改进,您可以使用collections.Counter对象完成此操作:

from collections import Counter
counts = Counter(x.lower().split())

现在,重复上面的循环。

答案 1 :(得分:0)

from collections import Counter
string = "Father father where art are thou"
new_list = string.lower().split()
get_value = Counter(new_list)
get_char_s = lambda x :'s' if x > 1 else ''
for k, v in get_value.items():
    print '%s is repeated %d time%s' % (k,v, get_char_s(v))
>>>thou is repeated 1 time
   where is repeated 1 time
   art is repeated 1 time
   father is repeated 2 times
   are is repeated 1 time

答案 2 :(得分:0)

您可以使用OrderedDict按照您的要求对dict对象进行排序。

这样:

from collections import OrderedDict
from operator import itemgetter

x = raw_input('Please enter a string: ').lower()#raw input for string to improve parsing.
def counter():
    counts = dict()
    words = str.split(x)

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1
    print(counts)
    d = OrderedDict(sorted(counts.items(), key=itemgetter(1),reverse =True))#Ordered Dict for sorting in reverse of keys like you like.
    print d
    return d

counter()

Output:
OrderedDict([('father', 2), ('thou', 1), ('where', 1), ('art', 1), ('are', 1)])

答案 3 :(得分:0)

我认为对代码进行一些修改也应该使用字符串格式,如下:

def counter():
    ...:     counts = dict()
    ...:     words = str.split(x)
    ...:     for word in words:
    ...:         if word in counts:
    ...:             counts[word] += 1
    ...:         else:
    ...:             counts[word] = 1
    ...:     print('father is repeated {counts[father]}\n \
    ...:             art is repeated {counts[art]}\n \
    ...:             are is repeated {counts[are]}\n \
    ...:             thou is repeated {counts[thou]}\n'.format(counts=counts))