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)
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With