[Tutor] newbie question

tpc@csua.berkeley.edu tpc@csua.berkeley.edu
Tue Apr 8 17:01:33 2003


Hello Danny, thank you for letting me know about the tutor list.  I have
joined and I thought I should direct this question to you since you wrote
the manual I am learning Python from.  On pages 12 and 13 you specify two
programs to take words from standard input, count how many times a word
appears, and print the results out:

import sys
from string import strip

words = []
while 1:
    w = strip(sys.stdin.readline())
    if not w: break
    words.append(w)
words.sort()

i=0
while i < len(words):
    current_word, count = words[i], 0
    while i < len(words) and words[i] == current_word:
        count = count + 1
        i = i + 1
    print current_word, count

and:

import sys
from string import strip

dict = {}
while 1:
    w = strip(sys.stdin.readline())
    if not w: break
    dict[w] = dict.get(w, 0) + 1

for word, count in dict.items():
    print word, count

The problem is when I try to run these programs standalone it seems to
hang and I have to hit Ctrl-d which gives me this message:

Traceback (most recent call last):
  File "/usr/local/apache2/htdocs/test.py", line 7, in ?
    w = strip(sys.stdin.readline())
KeyboardInterrupt

When I try to run the program with arguments from the command line it
hangs and I have to hit Ctrl-d which returns nothing:

[root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning
[root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning
[root@nike frsbapp]# /usr/local/apache2/htdocs/test.py good good morning

Am I doing something wrong ?