计算字符串中的字母频率 (Python) [英] Counting Letter Frequency in a String (Python)
问题描述
我正在尝试计算单词中每个字母出现的次数
I am trying to count the occurrences of each letter of a word
word = input("Enter a word")
Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0,26):
print(word.count(Alphabet[i]))
当前输出每个字母出现的次数,包括没有出现的次数.
This currently outputs the number of times each letter occurs including the ones that don't.
如何垂直列出字母及其旁边的频率,例如,如下所示?
How do I list the letters vertically with the frequency alongside it, e.g., like the following?
word=你好"
H 1
E 1
L 2
O 1
推荐答案
from collections import Counter
counts=Counter(word) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
for i in word:
print(i,counts[i])
尝试使用 Counter
,这将创建一个字典,其中包含集合中所有项目的频率.
Try using Counter
, which will create a dictionary that contains the frequencies of all items in a collection.
否则,只有当 word.count(Alphabet[i])
大于 0 时,您才可以对当前代码设置条件以print
,尽管那将是较慢.
Otherwise, you could do a condition on your current code to print
only if word.count(Alphabet[i])
is greater than 0, though that would be slower.
这篇关于计算字符串中的字母频率 (Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!