Hi... Pls, how do i do character occurrence using dictionary in python.
I want to count the number of each characters in a poem like this ..

A----25
G---10
etc...

Recommended Answers

All 3 Replies

Would 'Aa' count as A----2 or

A----1
a----1

?

A and a are treated as upper case. So Aa or AA would be counted as 2 because the letter a occur twice.

#!/usr/bin/env python
allthepoem = open ("c:\users\david\programming\python\poem.txt", "U").read()
allthepoem_upper_case = allthepoem.upper()
charslist = list(allthepoem_upper_case)
my_dict = dict()
for char in charslist:
    if ord(char) < 33: # space is chr(32), chr(10) is linefeed, chr(13) is carriage return, etc.
        char = "chr(" + str(ord(char)) + ")"
    if char in my_dict:
        my_dict[char] += 1
    else:
        my_dict[char] = 1
    
for char in my_dict:
    print char, " occurs ", my_dict[char], " times"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.