[Tutor] Major newbie question..

Gerrit Holl Gerrit Holl <gerrit@nl.linux.org>
Wed, 10 Nov 1999 14:30:34 +0100


Kevin Liang wrote:
> This might seem like a lame question, but I'm following a tutorial on a web page, and its at a point where you're
> 
> supposed to create a  program to count the words in a file.  As you can
> see, I'm a little stumped..any pointers/tips would be appreciated.   The
> thing runs, but not correctly.  I thought that adding .inp=
> resp.readlines(): would do the trick, but I guess not.  Thanks in
> advance
> 
> Kevin
> 
> import string
> def numwords(s):
>     list = string.split(s) # need to qualify split() with string module
>     return len(list) # return number of elements in list
> resp = raw_input("Enter a filename :  ")
> 
> inp = resp
> total = 0  # initialise to zero; also creates variable
> 
> for line in resp:
>     total = total + numwords(line) # accumulate totals for each line
> print "File had %d words" % total

You can do it much easier:

# untested code

import string
filename = raw_input("Enter filename: ")
filecontents = open(filename, 'r').read()
numwords = string.split(filecontents)
print "File had %d words" % numwords


I'm learning C and have just done it in C. Much more than 5 LOC :-)

Shortest way:

import string
print "File has %d words" % string.split(open(raw_input("Enter filename: "), 'r').read())


Only TWO LOC!

regards,
Gerrit.
-- 
linuxgames.nl.linux.org	 All about games on Linux in Dutch (under construction).
www.nl.linux.org	       The Dutch resource for Dutch Linux documentation.
www.nl.linux.org/discoverb		    Learn foreign words and definitions.
www.nl.linux.org/~gerrit/asperger	 I'm an Asperger, go here for more info.
www.nl.linux.org/~gerrit			    About me and pictures of me.