How to count letters in a text file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • nervusvagus
    New Member
    • Jan 2011
    • 4

    How to count letters in a text file?

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


    Code:
    # countletters.py
    
    def display(i):
    	if i == 10: return 'LF'
    	if i == 13: return 'CR'
    	if i == 32: return 'SPACE'
    	return chr(i)
    	
    infile = open('alice_in_wonderland.txt', 'r')
    text = infile.read()
    infile.close
    
    counts = 128* [0]
    for letter in text:
    	counts[ord(letter)]+=1
    outfile =open('alice_counts.dat','w')
    outfile.write("-12s%s\n" % ("Character","Count"))
    outfile.write("====================\n")
    for i in range(len(counts)):
    		if counts[i]:
    			outfile.write("%-12s%d\n" % (display(i), counts[i]))
    outfile.close()
    When I run this code I get the error:
    Code:
    Traceback (most recent call last):
      File "countletters.py", line 15, in <module>
        counts[ord(letter)]+=1
    IndexError: list index out of range

    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_wonder land.txt text file provided in this location: http://openbookproject.net/thinkcs/p...sh2e/ch10.html I get a different error:

    Code:
      File "countletters.py", line 18, in <module>
        outfile.write("-12s%s\n" % ("Character","Count"))
    TypeError: not all arguments converted during string formatting
    Last edited by nervusvagus; Jan 7 '11, 07:57 AM. Reason: update in error
  • nervusvagus
    New Member
    • Jan 2011
    • 4

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

    Comment

    • vijaya raghavan
      New Member
      • Jan 2011
      • 1

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

      Comment

      Working...