お題:4 wordcount.py
入力ファイル内の単語数をカウントして出力するプログラムを作成してくだ
さい。入力は全て標準入力、出力は標準出力。単語は1つ以上の文字列で、単語と単語の間は空白(スペースまたはタブ)もしくは改行で区切られているものとします。ハイフネーション(行末がハイフンで終わり続く行頭に単語が続くもの)は今回考慮しません。
VED03370 at nifty.ne.jpさんのお答え
import fileinput
i=0
for l in fileinput.input():
i=i+len(l.split())
print i
bravo at diana.dti.ne.jpさんのお答え
import sys, string
print len (string.split (sys.stdin.read ()))
fisher at r.hi-fi-net.comさんのお答え
#アルファベット、数字があるとスイッチオン、
#それ以外でスイッチオフ。スイッチオフの時にプラス
import sys
count = 0
pyswitch = "off"
for x in sys.stdin.read():
if pyswitch = "off":
if 48 <= ord(x) <= 57 or\
65 <= ord(x) <= 90 or\
97 <= ord(x) <= 122:
pyswitch = "on"
if pyswitch = "on":
if ord(x) <= 47 or\
58 <= ord(x) <= 64 or\
91 <= ord(x) <= 96 or 123 <= ord(x):
pyswitch = "off"
count = count + 1
if ord(x)
if pyswitch == "on":
count = count + 1
print count
fisher at r.hi-fi-net.comさんの正規表現使用バージョン
import sys, re
count = 0
pyswitch = "off"
for x in sys.stdin.read():
if pyswitch == "off":
if re.match("\w",x):
pyswitch = "on"
if pyswitch == "on":
if not re.match("\w",x):
pyswitch = "off"
count = count + 1
if pyswitch == "on":
count = count + 1
print count
ishimoto at gembook.orgさんのお答え
import sys, re
print len(re.findall(r"\S+", sys.stdin.read()))
|