-1

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...

2
Contributors
3
Replies
5
Views
7 Years
Discussion Span
Last Post by d5e5
0

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

Edited by Tops: n/a

1
#!/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"
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.