Counting Letter Frequency in a String (Python)

后端 未结 12 2108
既然无缘
既然无缘 2020-12-01 17:52

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


        
12条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 18:27

    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.

提交回复
热议问题