Hi, I've been asked to write a program using Python to count the number of words in a sentance. The exact task is outlined below:

Write a Python Program to count:
(i) the number of lines
(ii) the number of word
(iii) the number of character
in a text file and output the results in the following format:

Input filename: xxxxxx (the name of the input filename as provided by the user)
Total number of word: nnn
Total number of line: nnn
Total number of character: nnn

A “word” in this case is defined as a contiguous sequence of non-white-space characters (hint: split()). Character includes white (blank) spaces.

The input text file shall contain alphabet characters and white spaces only and could have any number of lines.

Can anybody help me?

Thank you!

Oh I'm sorry! I've done some if it as below, but I'm not sure what I need to add to excecute it, and if I'm even on the right track.

inFileName = 'test.txt'
infile = open(outFileName, 'r')
lineCount, wordCount, charCount =0,0,0
for line in infile.readlines():
    print line
    if line <> '/n':
        sum += float (line)
        wordCount +=1
        lineCount +=1
        charCount +=1
print 'This is a simple program that will provide you with infomation about your file!'
print 'Total number of word:' , wordCount
print 'Total number of line:' , lineCount
print 'Total number of character:' , charCount

Should I be using 'infile' function or should it be an 'outfile?' the 'test.txt' file is just a text file with some characters in it, but I'm unsure as to how I get the program to actualy read this file in order to count the words and characters.

Any assistance would be great, thank you


If you read your text file as one complete string (call it text), then you can do a couple of split() operations ...
line_list = text.split('\n')
word_list = text.split()
Now get the length of these lists ...
line_count = len(line_list)
word_count = len(word_list)

You are splitting the text string at the newline character to get the line list, and split the text string at all white spaces (including the newline char) to get the word list. Test-print the line_list and word_list to understand what the split() is doing.

To get the character count, you take the total length of the text and deduct the newline_count. Simply count the number of '\n' in the text, there is a string function to do that.

When you have all your counts you have to create a string that contains your formatted answer and save/write it it to your out_file.