
はじめに
第12回では「ファイル結合ツール」を作って、複数のテキストを1つにまとめる方法を学んだな。
今回はちょっとしたデータ分析の入り口として、「単語カウントアプリ」 を作るで!
テキストの中に登場する単語の数を数えて、どの単語がよく使われているかを調べられるんや。
完成イメージ
テキストファイル(sample.txt
):
Pythonは楽しい。Pythonでアプリを作ろう。
プログラムの出力:
{'Pythonは楽しい。': 1, 'Pythonでアプリを作ろう。': 1}
単語単位で分割する方法を工夫すれば、もっと自然なカウントもできるで。
ヒント(使う要素)
open("ファイル名", "r")
→ ファイルを読み込み.split()
→ 文字列を空白で分割dict
(辞書型) → 単語ごとの出現回数を記録for
文 → 単語を1つずつ処理
コード全文(基本版)
# Lesson 13: 単語カウントアプリ(基本版) filename = "sample.txt" with open(filename, "r", encoding="utf-8") as f: text = f.read() words = text.split() # 空白で分割 counts = {} for word in words: if word in counts: counts[word] += 1 else: counts[word] = 1 print(counts)
改良版(きれいに表示)
# Lesson 13: 単語カウントアプリ(改良版) filename = "sample.txt" with open(filename, "r", encoding="utf-8") as f: text = f.read() words = text.split() counts = {} for word in words: counts[word] = counts.get(word, 0) + 1 print("--- 単語カウント結果 ---") for word, count in counts.items(): print(f"{word}: {count}")
応用アイデア
.lower()
を使って大文字小文字を区別せずに数える- 記号を削除してカウントを正確にする(
replace()
などを活用) collections.Counter
を使うともっと簡単に書ける
from collections import Counter print(Counter(words))
まとめ
今回は 「単語カウントアプリ」 を作って、文字列処理と辞書型の使い方を学んだで!
テキスト分析の第一歩としてピッタリやな。
👉 次回は Lesson 14: CSV読み込み→合計計算アプリ。
ファイル操作を使ってデータを読み込み、計算する仕組みに挑戦や!