Counting Letter Frequency in a String (Python)

戏子无情 提交于 2019-11-28 06:20:40

问题


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


回答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])

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.




回答2:


def char_frequency(str1):
    dict = {}
    for n in str1:
        keys = dict.keys()
        if n in keys:
            dict[n] += 1
        else:
            dict[n] = 1
    return dict
print(char_frequency('google.com'))



回答3:


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}



回答4:


s=input()
t=s.lower()

for i in range(len(s)):
    b=t.count(t[i])
    print("{} -- {}".format(s[i],b))



回答5:


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




回答6:


Following up what LMc said, your code was already pretty close to functional, you just needed to post-process the result set to remove 'uninteresting' output. Here's one way to make your code work:

#!/usr/bin/env python
word = raw_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'
]

hits = [
    (Alphabet[i], word.count(Alphabet[i]))
    for i in range(len(Alphabet))
    if word.count(Alphabet[i])
]

for letter, frequency in hits:
    print letter.upper(), frequency

But the solution using collections.Counter is much more elegant/Pythonic.




回答7:


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


来源:https://stackoverflow.com/questions/40985203/counting-letter-frequency-in-a-string-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!