Counting Letter Frequency in a String (Python)

2020-02-13 04:37发布

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:

word="Hello"

H 1

E 1

L 2

O 1

8条回答
等我变得足够好
2楼-- · 2020-02-13 04:51

For future references: When you have a list with all the words you want, lets say wordlistit's pretty simple

for numbers in range(len(wordlist)):
    if wordlist[numbers][0] == 'a':
        print(wordlist[numbers])
查看更多
神经病院院长
3楼-- · 2020-02-13 04:53

easy and simple solution without lib.

string=input()
f={}
for i in string:
  f[i]=f.get(i,0)+1
print(f)

here is the link for get() https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html

查看更多
迷人小祖宗
4楼-- · 2020-02-13 04:55

As @Pythonista said, this is a job for collections.Counter:

from collections import Counter
print(Counter('cats on wheels'))

This prints:

{'s': 2, ' ': 2, 'e': 2, 't': 1, 'n': 1, 'l': 1, 'a': 1, 'c': 1, 'w': 1, 'h': 1, 'o': 1}
查看更多
神经病院院长
5楼-- · 2020-02-13 04:59

If using libraries or built-in functions is to be avoided then the following code may help:

s = "aaabbc"  # sample string
dict_counter = {}  # empty dict for holding characters as keys and count as values
for char in s:  # traversing the whole string character by character
    if not dict_counter or char not in dict_counter.keys():  # Checking whether the dict is
        # empty or contains the character
        dict_counter.update({char: 1})  # if not then adding the character to dict with count = 1
    elif char in dict_counter.keys():  # if the char is already in the dict then update count
        dict_counter[char] += 1
for key, val in dict_counter.items(): # Looping over each key and value pair for printing
    print(key, val)

Output:
a 3
b 2
c 1

查看更多
6楼-- · 2020-02-13 05:01
s=input()
t=s.lower()

for i in range(len(s)):
    b=t.count(t[i])
    print("{} -- {}".format(s[i],b))
查看更多
可以哭但决不认输i
7楼-- · 2020-02-13 05:02
from collections import Counter
counts=Counter(word) # Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
for i in word:
    print(i,counts[i])

Try using Counter, which will create a dictionary that contains the frequencies of all items in a collection.

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

查看更多
登录 后发表回答