1

我正在为问题的表格部分中的打印而苦苦挣扎。到目前为止,我已经设法按字母顺序对用户输入的句子进行排序,并计算每个单词出现的次数。这是代码:

thestring = (raw_input())
sentence = thestring.split(" ")
sentence.sort()

count = {}
for word in thestring.split():
    try: count[word] += 1
    except KeyError: count[word] = 1

print sentence
print count

当我运行代码时,我得到了这个:

['apple', 'apple', 'banana', 'mango', 'orange', 'pear', 'pear', 'strawberry']
{'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}

但是,理想情况下,我希望它打印在一个看起来像这样的表格中:

apple.....|.....2
banana....|.....1
mango.....|.....1
orange....|.....1
pear......|.....2
strawberry|.....1

谢谢你的帮助!

4

5 回答 5

5

format是打印格式化字符串的pythonic方式:

d = {'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}

for word, count in sorted(d.items()):
    print "{:20} | {:5}".format(word, count)

要自动调整第一列的大小:

maxlen = max(map(len, d))
for word, count in sorted(d.items()):
    print "{:{}} | {}".format(word, maxlen, count)

如果你真的想用点(或其他)填充它,那么就像这样:

for word, count in sorted(d.items()):
    print "{:.<{}}|{:.>5}".format(word, maxlen, count)
苹果.....|....2
香蕉....|....1
芒果.....|....1
橙色....|....1
梨......|....2
草莓|....1

正如已经指出的,对于第一部分,最好使用Counter.

于 2013-10-25T09:47:54.790 回答
3
sentence = thestring.split(" ")
from collections import Counter
for fruit, num in sorted(Counter(sentence).items()):
    print "{:10}|{:5}".format(fruit.ljust(10, "."), str(num).rjust(5, "."))

输出

apple.....|....2
banana....|....1
mango.....|....1
orange....|....1
pear......|....2
strawberry|....1

您可以使用格式示例来了解它的工作原理。

于 2013-10-25T09:52:09.967 回答
2

您应该collections.Counter为此使用:

from collections import Counter

thestring = (raw_input()).split(" ")
cnt = Counter(thestring)
items = cnt.items()
items.sort(key=lambda x: x[0])
print items
于 2013-10-25T09:43:19.300 回答
0

Counter是更好的解决方案,但如果你想坚持你的代码,只需替换print count

for c in sorted(count): 
    print c + '.'*(10-len(c))+'|'+'.'*(6-len(str(count[c])))+str(count[c])
于 2013-10-25T09:41:27.953 回答
0
d = {'apple': 2, 'pear': 2, 'strawberry': 1, 'mango': 1, 'orange': 1, 'banana': 1}
for v,k in d.items():
  s = str(v).ljust(l, '.') + "|" + str(k).rjust(10, '.')
  print s

其中 l 是 u 最长键的长度。

在输出上你有:

apple.....|.........2
pear......|.........2
strawberry|.........1
mango.....|.........1
orange....|.........1
banana....|.........1
于 2013-10-25T09:50:41.587 回答