Newbie: word count and Win32
Bengt Richter
bokr at oz.net
Tue Mar 19 15:26:34 EST 2002
On 19 Mar 2002 04:21:10 -0800, jchristl at zdnetmail.com (Joe Christl) wrote:
>newbie here (don't you just cringe when you read that? :),
>
>I downloaded the python EXE from
>http://www.python.org/ftp/python/2.2/, found a script on the
>mail.python.org Tutor page:
>http://mail.python.org/pipermail/tutor/2001-February/003403.html
^...[1]
>
>but I can't seem to get it to run. I would like it to run from the
>C:\ command prompt, like so:
>
>c:\count.py foo.txt (or)
>c:\count.pyc foo.txt
>
>and have it output the lines, words, and characters. I have tried to
>even get it working from the >>> prompt, to no avail.
>
>Am I doing something wrong here?
>
>From a quick look that[1] script, it looks like it expects to read
from stdin only. I.e., it says
# iterate over each line on stdin
for line in sys.stdin.readlines() :
...
To feed the script's stdin you'll have to redirect or pipe data to it.
To pipe stuff on windows to a python script you have to run the interpreter
(python) explicitly one way or another, so I would try:
python count.py < foo.txt
or you could pipe the output of the windows type command, like:
type foo.txt | python count.py
To make the script work like what you expected, it needs to look
at the command line arguments (sys.argv) for a file name and open that,
and use the resulting file object in place of stdin.
BTW, IMO you get a nicer ouput if you change the last line of the script to
print '%6d: %s' % (words[word], word)
As an exercise, you could modify it to accept an option on the command line
to output in order of frequency instead of alphbetically, and also accept
a file name. Then look into the glob module and see if you can make it
do multiple files from a wild card spec. Have fun.
You may want to look at various scripts that were put on your disk when
you installed, e.g. in wahtever corresponds to D:\Python22\Tools\Scripts\*
on your system. Look at some small stuff first.
Regards,
Bengt Richter
More information about the Python-list
mailing list