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:
When I run this code I get the error:
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:
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()
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
Comment