So far I only have text: aaaaa bbbb cccc
in the text file:
Expand|Select|Wrap|Line Numbers
- # 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()
Expand|Select|Wrap|Line Numbers
- 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_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
- File "countletters.py", line 18, in <module>
- outfile.write("-12s%s\n" % ("Character","Count"))
- TypeError: not all arguments converted during string formatting