By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,089 Members | 2,260 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,089 IT Pros & Developers. It's quick & easy.

How to count letters in a text file?

P: 4
Following is a code that counts the number of letters in a text file named "alice_in_wonderland.txt"
So far I only have text: aaaaa bbbb cccc
in the text file:


Expand|Select|Wrap|Line Numbers
  1. # countletters.py
  2.  
  3. def display(i):
  4.     if i == 10: return 'LF'
  5.     if i == 13: return 'CR'
  6.     if i == 32: return 'SPACE'
  7.     return chr(i)
  8.  
  9. infile = open('alice_in_wonderland.txt', 'r')
  10. text = infile.read()
  11. infile.close
  12.  
  13. counts = 128* [0]
  14. for letter in text:
  15.     counts[ord(letter)]+=1
  16. outfile =open('alice_counts.dat','w')
  17. outfile.write("-12s%s\n" % ("Character","Count"))
  18. outfile.write("====================\n")
  19. for i in range(len(counts)):
  20.         if counts[i]:
  21.             outfile.write("%-12s%d\n" % (display(i), counts[i]))
  22. outfile.close()
  23.  
When I run this code I get the error:
Expand|Select|Wrap|Line Numbers
  1. Traceback (most recent call last):
  2.   File "countletters.py", line 15, in <module>
  3.     counts[ord(letter)]+=1
  4. IndexError: list index out of range
  5.  

Even though this example is straight out of the book How to Think Like a Computer Scientist Learning with Python 2nd Edition. Could someone help me find what is wrong with this code?

UPDATE:
When I run the code with the alice_in_wonderland.txt text file provided in this location: http://openbookproject.net/thinkcs/p...sh2e/ch10.html I get a different error:

Expand|Select|Wrap|Line Numbers
  1.   File "countletters.py", line 18, in <module>
  2.     outfile.write("-12s%s\n" % ("Character","Count"))
  3. TypeError: not all arguments converted during string formatting
  4.  
Jan 7 '11 #1
Share this Question
Share on Google+
2 Replies


P: 4
This seems to work now with the given text file and the given code, with no apparent reason. Not sure why I was getting the errors above.
Jan 7 '11 #2

P: 1
U missed % symbol before "-12s%s\n" it should be like "%-12s%s\n"

See The Reason is.. U are passing two arguments for writing it, As the % is not there it considered as string and so only one argument get converted to actual value.. and another one not converted...
In python u will get meaningful error.. try understand the error .. u can solve anything...
Jan 21 '11 #3

Post your reply

Sign in to post your reply or Sign up for a free account.