944,156 Members | Top Members by Rank

Ad:
  • Python Code Snippet
  • Views: 1473
  • Python RSS
1

Letter frequency function using lists

by on Oct 19th, 2009
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.
Python Code Snippet (Toggle Plain Text)
  1. def letterFrequency():
  2.  
  3. newString = raw_input( "Type the string here: " )
  4.  
  5. #Convert to lowercase
  6. mod_string = newString.lower()
  7.  
  8. #Initialize lists to store the new data in
  9. data = []
  10. new_data = []
  11. count = 0
  12.  
  13. #Check only for characters in the given string
  14. for s in 'abcdefghijklmnopqrstuvwxyz':
  15. count = 0
  16. for char in mod_string:
  17. if s == char:
  18. count += 1
  19.  
  20. data = [ s, count ]
  21. new_data += [ data ]
  22.  
  23. return new_data
  24.  
  25. print letterFrequency()
Comments on this Code Snippet
Oct 20th, 2009
0

Re: Letter frequency function using lists

You may not want to add letters to the list that have zero count.
Nearly a Posting Virtuoso
bumsfeld is offline Offline
1,422 posts
since Jul 2005
Oct 20th, 2009
0

Re: Letter frequency function using lists

yeah you're right a quick fix would be to add an if statement in line 19, like
Python Syntax (Toggle Plain Text)
  1. if count > 0:
  2. data = [ s, count ]
  3. new_data += [ data ]

thanks
Posting Whiz in Training
masterofpuppets is offline Offline
272 posts
since Jul 2009
Oct 20th, 2009
0

Re: Letter frequency function using lists

You can use str.count(sub, [, start [, end]]) to count the instances of a substring in a string.
Posting Whiz in Training
lrh9 is offline Offline
238 posts
since Oct 2009
Message:
Previous Thread in Python Forum Timeline: Clearing the screen of text
Next Thread in Python Forum Timeline: Draw a random number once from a set of random numbers.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC