0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ミニプロジェクト2:テキスト分析ツール【Day 24】

Last updated at Posted at 2025-12-23

Qiita Advent Calendar 2025 のパイソニスタの一人アドカレ Day24 の記事です。

ミニプロジェクト2:テキスト分析ツール

Python を使って、簡単な テキスト分析ツール を作ってみましょう。
今回は 文章の文字数・単語数・行数 を数えるプログラムを作ります。

1. 基本の考え方

やりたいこと:

  1. ユーザーからファイル名を入力してもらう
  2. ファイルを開いて内容を読み込む
  3. 文字数・単語数・行数を計算する
  4. 結果を表示する

2. サンプルコード

def analyze_text():
    filename = input("分析するファイル名を入力してください: ")

    try:
        with open(filename, "r", encoding="utf-8") as f:
            content = f.read()
    except FileNotFoundError:
        print("ファイルが存在しません")
    except Exception as e:
        print("エラーが発生しました:", e)

        num_chars = len(content)  # 文字数
        num_lines = content.count("\n") + 1  # 行数
        num_words = len(content.split())  # 単語数(空白区切り)

        print("文字数:", num_chars)
        print("単語数:", num_words)
        print("行数:", num_lines)

analyze_text()

3. ポイント解説

  • with open:ファイルを安全に開く
  • read():ファイル全体を文字列として読み込む
  • len():文字数を数える
  • split():空白で単語に分割
  • count("\n") + 1:行数を数える
  • try-except:ファイルが存在しない場合やその他のエラーに対応

4. 改良アイデア

  • 行ごとに文字数や単語数を表示
  • 単語の出現頻度をカウント
  • 入力を複数ファイルに対応させる
  • 英数字だけカウントしたり日本語だけ抽出したりする

5. まとめ

  • ファイル操作、文字列操作、例外処理を組み合わせた練習になる
  • 自分の文章やデータを分析することで、Python の便利さを実感できる
  • 小さなプロジェクトでも学びが多いので、ぜひ改良してみよう
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?