[python] お題2: 単語数のカウント
英文のテキストファイルを読み込んで単語の出現数を数えるプログラムを作れ。
例えばテキストファイルの中身が「It's fine day, isn't it? Yes, it is!」ならばit'sが1回、fineが1回、dayが1回、isn'tが1回、itが2回、yesが1回、isが1回となるように数えてよい。
(isn'tにはisが含まれているな、とか、It'sの'sはisの省略形だな、などと判断するのはとてもむずかしいので)
余力があれば出現頻度の多い順に出力するプログラムも書け。
うわ~、頻度順じゃなくてアルファベット順で書いてしまったよ orz
import sys, string
try:
globals().__setitem__( "file_object", open( sys.argv[1] ) )
except IOError:
print "指定されたファイルが見つかりません。"
sys.exit()
words_counter = {}
for line in file_object:
for single_word in line.split():
single_word = string.upper( single_word )
words_counter.update( single_word=(words_counter[single_word] + 1) ) if single_word in words_counter else words_counter.__setitem__( single_word, 1 )
maximum_length = max( [len( key ) for key in words_counter] )
total_amount = reduce( lambda x, y: x + y, words_counter.values() )
print "Total%s%6s words" % (chr( 0x20 ) * (maximum_length - len( "Total" )), total_amount)
found_words = words_counter.keys()
found_words.sort()
for word in found_words:
print "%s%s%6s words ( %s %% )" % (word, (chr( 0x20 ) * (maximum_length - len( word ))), words_counter[word], (words_counter[word] / float(total_amount) * 100.0))
後で書き直すかも。
| 固定リンク
トラックバック
この記事のトラックバックURL:
http://app.cocolog-nifty.com/t/trackback/103108/15549579
この記事へのトラックバック一覧です: [python] お題2: 単語数のカウント:

コメント