Home > Programming > Word Count program in Python

Word Count program in Python


Opening a file in python is very easy. This is the easiest way I’ve ever done before. Python has an in built function called “open” which will open the file for you and then onwards we can do all the operations as we want. Same as C language open function Python “open()” also takes file name as input and the mode it has to operate on that file like “read”, “write” or “append”. Here I would like to give the code for counting the number of words in a given file.

#Author: Vasanth Raja Chittampally
def filePro(filename):
	f=open(filename,'r')
	wordcount=0
	for lines in f:
		 f1=lines.split()
		 wordcount=wordcount+len(f1)
	f.close()
	print 'word count:', str(wordcount)
filePro(raw_input("enter file name:"))

Like other lists, file can also be used in the for loop as another simple list. as shown in the above program.

Advertisements
  1. Anon
    January 27, 2015 at 11:31 am

    Line 7 can be more concisely stated as: wordcount += len(f1)

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: