473,413 Members | 2,058 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,413 software developers and data experts.

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_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
2 7351
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
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

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

Similar topics

3
by: Cherif Diallo | last post by:
Hi I have a trivial question for the experts. I would lilke to read be able to read a text file that could contain french characters with accents. I'm opening the file with the...
1
by: wtnt | last post by:
Hello. I've searched all over and haven't seen another thread with this problem. Please bear with me as I try to explain. thanks. :) I have some programs that need to be cross-platform...
14
by: nic977 | last post by:
I am asked to write a simple program to displays the last n lines from a given text file. But I have no ideas how C defines a "line" in a text file. How does it tell if it is the end of the line,...
3
by: I_AM_DON_AND_YOU? | last post by:
In my program I am using the notepad file to read/write data. I don't want that someone should be able to delete/change the contents of that file by opening that file in Notepad or other editor. ...
5
by: andy.lee23 | last post by:
hi im having trouble counting lines in a text file, i have the following code int node1, node2, i; char name; float value; ifstream fin; fin.open(OpenDialog1->FileName.c_str()); i=1;
4
by: bigbagy | last post by:
Notes The programs will be compiled and tested on the machine which runs the Linux operating system. V3.4 of the GNU C/C++ compiler (gcc ,g++) must be used. A significant amount coding is...
39
by: Umesh | last post by:
Plese help. Is there any software by which we can do that?
2
by: Cliff72 | last post by:
I'm creating a database that will be uploading some text files into an access table. The problem is that the text files have a header which messes up my import specs. so what i have had to do is to...
2
by: charlesbritto | last post by:
A C++ program for counting individual string in a text file using file handling functions., for ex: if the text file contains, am a boy,am studying +2,am from chennai Now the result shoud...
1
by: stoogots2 | last post by:
I have written a Windows App in C# that needs to read a text file over the network, starting from the end of the file and reading backwards toward the beginning (looking for the last occurrence of a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.