python program to print the no. of occurences of a 'character' in a sentence
import pprint#python program to print the no. of occurances of a word in a sentence
message = 'I am captain Neel jack sparrow. the quest for knowledge is a never ending process'
# first define a dictonary
count = {}
# loop for each character in message
for character in message:
# if the character is not present in the dictionary, it will be stored
# and the default value will be set to 0.
# if the character is already present, the default value 0 will not be set.
count.setdefault(character, 0)
# in the dictionary, character is the key and value is the no. of it's occurance
# increment the value by 1 for each key i.e character
count[character] = count[character] + 1
#pretty printing
pprint.pprint(count)
Output:
{' ': 14,
'.': 1,
'I': 1,
'N': 1,
'a': 6,
'c': 3,
'd': 2,
'e': 10,
'f': 1,
'g': 2,
'h': 1,
'i': 3,
'j': 1,
'k': 2,
'l': 2,
'm': 1,
'n': 5,
'o': 4,
'p': 3,
'q': 1,
'r': 5,
's': 5,
't': 3,
'u': 1,
'v': 1,
'w': 2}
{' ': 14,
'.': 1,
'I': 1,
'N': 1,
'a': 6,
'c': 3,
'd': 2,
'e': 10,
'f': 1,
'g': 2,
'h': 1,
'i': 3,
'j': 1,
'k': 2,
'l': 2,
'm': 1,
'n': 5,
'o': 4,
'p': 3,
'q': 1,
'r': 5,
's': 5,
't': 3,
'u': 1,
'v': 1,
'w': 2}
'.': 1,
'I': 1,
'N': 1,
'a': 6,
'c': 3,
'd': 2,
'e': 10,
'f': 1,
'g': 2,
'h': 1,
'i': 3,
'j': 1,
'k': 2,
'l': 2,
'm': 1,
'n': 5,
'o': 4,
'p': 3,
'q': 1,
'r': 5,
's': 5,
't': 3,
'u': 1,
'v': 1,
'w': 2}
{' ': 14,
'.': 1,
'I': 1,
'N': 1,
'a': 6,
'c': 3,
'd': 2,
'e': 10,
'f': 1,
'g': 2,
'h': 1,
'i': 3,
'j': 1,
'k': 2,
'l': 2,
'm': 1,
'n': 5,
'o': 4,
'p': 3,
'q': 1,
'r': 5,
's': 5,
't': 3,
'u': 1,
'v': 1,
'w': 2}