Letter frequency function using lists


A simple function to return the number of occurances of a letter in a text. An easier way to implement this would be by using a dictionary :)

P.S sorry if there already is a code snipped like that somewhere.

About the Author

Hi all I am a second year student in the University of Glasgow so I am still a noobie in programming but I am trying my best sofar and I am happy to help.
So, I am sorry if I make silly mistakes in my programs.

def letterFrequency():

    newString = raw_input( "Type the string here: " )

    #Convert to lowercase
    mod_string = newString.lower()

    #Initialize lists to store the new data in
    data = []
    new_data = []
    count = 0

    #Check only for characters in the given string
    for s in 'abcdefghijklmnopqrstuvwxyz':
        count = 0
        for char in mod_string:        
            if s == char:
                count += 1

        data = [ s, count ]
        new_data += [ data ]    
    return new_data

print letterFrequency()
bumsfeld 413 Nearly a Posting Virtuoso

You may not want to add letters to the list that have zero count.

masterofpuppets 19 Posting Whiz in Training

yeah you're right a quick fix would be to add an if statement in line 19, like

if count > 0:
   data = [ s, count ]
   new_data += [ data ]

thanks :)

lrh9 95 Posting Whiz in Training

You can use str.count(sub, [, start [, end]]) to count the instances of a substring in a string.

Be a part of the DaniWeb community

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