結城さんからトラックバックを頂いた。Haskellもかなりシンプルに書けるんですね。いつか勉強するときがくるかもしれないです。
さて、しばらくは標準出力から取得した文字列で遊んでみることとする。
countwords.py
def countwords(s): count = 0 space = " " index = -1 for i in range(len(s)): if i > index: if s[i] != space: for j in range(i,len(s)): if (s[j] == space) or (j == len(s) - 1): count += 1 index = j break return count while(1): s = raw_input() if s == '': break c = countwords(s) if c > 1: print 'The string has %d words' % (c) else: print 'The string has just %d word' % (c)
実行結果
C:\Python24>python.exe countwords.py This is a pen The string has 4 words My Name is John The string has 4 words It's nice to meet you! The string has 5 words
空白が多かったときなどの処理に気をつけなければならなかったので、少し苦戦。
しかし遊びのプログラムは本当に楽しい。