输入一个句子并计算每个字母?

时间:2013-12-05 18:25:10

标签: python python-2.7

所以基本上我需要程序来计算每个字母在一个句子中的使用次数。 我发现的唯一一件就是这个,而且很难看:

from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
print counter['a']
print counter['b']
print counter['c']
print counter['d']
print counter['e']
print counter['f']
#etc to z

有更简单的方法吗????

6 个答案:

答案 0 :(得分:2)

假设我理解你:

>>> from collections import Counter
>>> from string import ascii_lowercase
>>> s = "Mary had a little lamb"
>>> counts = Counter(s.lower())
>>> for letter in ascii_lowercase:
...     print letter, counts[letter]
...     
a 4
b 1
c 0
[...]
x 0
y 1
z 0

请注意,我将字符串小写,以便m给出2;如果您不想这样,请删除.lower()并改为使用string.ascii_letters

答案 1 :(得分:1)

您只需循环遍历所有小写字母,并打印出每个字母的计数:

>>> from collections import Counter
>>> sentence = "Mary had a little lamb"
>>> counter = Counter(sentence)
>>> from string import ascii_lowercase
>>> for letter in ascii_lowercase:
...     print '{} = {}'.format(letter, counter[letter])
a = 4
b = 1
c = 0
d = 1
e = 1
f = 0
g = 0
h = 1
i = 1
j = 0
k = 0
l = 3
m = 1
n = 0
o = 0
p = 0
q = 0
r = 1
s = 0
t = 2
u = 0
v = 0
w = 0
x = 0
y = 1
z = 0

答案 2 :(得分:1)

如果您只想打印有关字符串中实际字符的信息,可以采用一种简单的方法

for key in sorted(counter.keys()):
    print("{0} appears {1} times.".format(key, counter[key]))

结果:

  appears 4 times.
M appears 1 times.
a appears 4 times.
b appears 1 times.
d appears 1 times.
e appears 1 times.
h appears 1 times.
i appears 1 times.
l appears 3 times.
m appears 1 times.
r appears 1 times.
t appears 2 times.
y appears 1 times.

请注意,空格字符也会计算在内。

答案 3 :(得分:1)

from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
for c in set(str):
    print '%s -> %d' % (c, counter[c])

答案 4 :(得分:0)

import string
from collections import Counter
str = "Mary had a little lamb"
counter = Counter(str)
for letter in string.lowercase:
    print counter[letter]

答案 5 :(得分:0)

请参阅this answer,它将为您提供如何创建一系列字符的示例。然后只需使用foreach循环:

for item in letters_a_to_z:
    print counter[item]