7

I'm just getting into Python and I'm building a program that analyzes a group of words and returns how many times each letter appears in the text. i.e 'A:10, B:3, C:5...etc'. So far it's working perfectly except that i am looking for a way to condense the code so i'm not writing out each part of the program 26 times. Here's what I mean..

print("Enter text to be analyzed: ")
message = input()

A = 0
b = 0
c = 0
...etc

for letter in message:

    if letter == "a":
        a += 1
    if letter == "b":
        b += 1
    if letter == "c":
        c += 1
    ...etc

print("A:", a, "B:", b, "C:", c...etc)
1
  • 1
    Use a dict instead of 26 variables. Commented Sep 14, 2013 at 3:17

2 Answers 2

13

There are many ways to do this. Most use a dictionary (dict). For example,

count = {}
for letter in message:
    if letter in count:  # saw this letter before
        count[letter] += 1
    else:   # first time we've seen this - make its first dict entry
        count[letter] = 1

There are shorter ways to write it, which I'm sure others will point out, but study this way first until you understand it. This sticks to very simple operations.

At the end, you can display it via (for example):

for letter in sorted(count):
    print(letter, count[letter])

Again, there are shorter ways to do this, but this way sticks to very basic operations.

Sign up to request clarification or add additional context in comments.

2 Comments

So we can also remove if-else as count[letter] = count.setdefault(letter, 0) + 1 . correct na?
Yes, setdefault() instead works fine - that's what it's for. But it's harder for newcomers to understand, so I avoided it here :-)
12

You can use Counter but @TimPeters is probably right and it is better to stick with the basics.

from collections import Counter

c = Counter([letter for letter in message if letter.isalpha()])
for k, v in sorted(c.items()):
    print('{0}: {1}'.format(k, v))

2 Comments

Yours is an excellent answer! It's what a Python expert would do. My hope is that studying my "sticking to the basics" answer will help the poster learn more about Python-the-language - collections.Counter pretty much solves the entire problem by magic ;-)
yeah... I think i'll be sticking with the basics for now but I think I might try to experiment with this a bit! Could be useful later on. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.