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

标签 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

有没有更简单的方法来做到这一点????

最佳答案

假设我理解你:

>>> 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

关于python - 输入一个句子并计算每个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20407756/

相关文章:

python - 获取掩码数组的最小值

python - 使用 Watson 对本地文件进行视觉识别

python-2.7 - 在窗口和远程 X11 中将 Tkinter 顶级窗口居中?

python - 如何使用Python子进程捕获子进程的错误?

python - 每次运行在变量之间交替

python - 有没有办法告诉 matplotlib 放松对绘制数据的缩放?

python - 在 Python 中导入所花费的时间

python - 将 csv 转换为具有多个值的字典?

python - 执行 python 脚本后额外的零

Python大列表和输入数据库