Python program to count unique letters in any given string or paragraph



To count the unique letters in any given string and paragraph we can use python dictionary object and its indexing method. Below the program of counting unique alphabets, white spaces and dashes.

Python Program or code:

import string
#Include " " to count it
alphabet = string.ascii_letters + " " + " -- "
#print(alphabet)

sentence = 'Jim quickly realized that the beautiful gowns are expensive'
address = """Four score and seven years ago our fathers brought forth on this continent, a new nation, 
conceived in Liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a 
great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. 
We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final 
resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper 
that we should do this. But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- 
this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add 
or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. 
It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so 
nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored 
dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here 
highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of 
freedom -- and that government of the people, by the people, for the people, shall not perish from the earth."""


count_letters = {}
#print(len(sentence))

def counter(input_string):
    for i in range(len(alphabet)):
        count_letters[alphabet[i]] = input_string.count(alphabet[i])
    return count_letters

c1 = counter(sentence)
print(c1)

c2 = counter(address)
print(c2)

Explanation:

In above code in first line we import string library to work with string. And in second line we use ascii_letters method of string to get the alphabets both uppercase and lower case inclusive.  An ascii_letters method does not provide " " white space and "--" dashes so we added it with out ascii_letters method and finally stored that it in to variable alphabet.

Second and third line, sentence and address is our string and paragraph to search the unique letters.
Note: Bothe are used with separate function call and you can change its content of string according your need. For example in 'sentence' variable you can change the sentence and similarly in alphabet variable you can change the paragraph.

Now we declare one empty dictionary named as count_letters{}. In this dictionary we will store each of alphabet and its count in given string as a 'key:value' pair.

In the next line we defined a function named  'counter' which takes a string as input and we initialize its variable as 'input_string'. In that function we defined a for loop to run up to total length of the alphabets, in our case alphabets capital 'A' to 'Z' and and lowercase 'a' to 'z' and white space and dashes also. Then we used python string method 'count' to count the occurrence of particular letter in input string. Here alphabet[i] updates each times the loops run with one by one new alphabet characters. For example in first iteration it will be alphabet['a'] and in second iteration it will be alphabet['b'] and so on. Then 'count' method will return total occurrences in given input string. Then we will store as a key of 'count_letters' dictionary same as iteration of'[alphabet[i]' explained just above lines. The only difference is this 'key' will add the new content or append dictionary every time for loop runs. And then we return the 'count_letters' dictionary.

We can now call the function counter(sentence) to get the unique letters count and similarly counter(address) to get count from paragraph. And then save the result in variable 'c1' and 'c2' respectively.

Output of the code expected as below:
 {'a': 4, 'b': 1, 'c': 1, 'd': 1, 'e': 8, 'f': 1, 'g': 1, 'h': 2, 'i': 5, 'j': 0, 'k': 1, 'l': 3, 'm': 1, 'n': 2, 'o': 1, 'p': 1, 'q': 1, 'r': 2, 's': 2, 't': 4, 'u': 3, 'v': 1, 'w': 1, 'x': 1, 'y': 1, 'z': 1, 'A': 0, 'B': 0, 'C': 0, 'D': 0, 'E': 0, 'F': 0, 'G': 0, 'H': 0, 'I': 0, 'J': 1, 'K': 0, 'L': 0, 'M': 0, 'N': 0, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 0, 'U': 0, 'V': 0, 'W': 0, 'X': 0, 'Y': 0, 'Z': 0, ' ': 8, '-': 0}
 
{'a': 102, 'b': 13, 'c': 31, 'd': 58, 'e': 165, 'f': 26, 'g': 27, 'h': 80, 'i': 65, 'j': 0, 'k': 3, 'l': 41, 'm': 13, 'n': 76, 'o': 93, 'p': 15, 'q': 1, 'r': 79, 's': 44, 't': 124, 'u': 21, 'v': 24, 'w': 26, 'x': 0, 'y': 10, 'z': 0, 'A': 0, 'B': 1, 'C': 0, 'D': 0, 'E': 0, 'F': 1, 'G': 1, 'H': 0, 'I': 3, 'J': 0, 'K': 0, 'L': 1, 'M': 0, 'N': 1, 'O': 0, 'P': 0, 'Q': 0, 'R': 0, 'S': 0, 'T': 2, 'U': 0, 'V': 0, 'W': 2, 'X': 0, 'Y': 0, 'Z': 0, ' ': 277, '-': 15}
 
Reference: Edx course HarvardX PH526x Using Python for Research [edx.org] | Homework1 quiz answer.


4 comments:
  1. Thank you, i was stuck in quizzes.

    ReplyDelete
  2. This handy python program counts the number of occurrences of any given letter within a string or paragraph. Simply type any text into the provided text box, select a letter from the dropdown menu, then press GO! In this python program, we read from standard input with line breaks, count all unique letters with split(), count number of occurrences with sum(), then output total letters found

    ReplyDelete
  3. Thanks for edx quiz answer!

    ReplyDelete