0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

私のプロンプト「あなたは優秀なPythonエンジニアというGeminiです。高度な文字数チェッカー作れるプロンプトを作ってください」 Gemini「もちろんです!」

0
Last updated at Posted at 2026-05-11

私はKindleのMarkdownの文字数チェッカーが欲しかったのです。
しかし、どのようにプロンプトを送ればそのような文字数チェッカーを手に入れるか分かりませんでした。
ですので以下のようなソースコードを送り、どのようにすれば、このようなコードが手に入るのかを聞きました。

Geminiに出したプロンプトと提示したコード

このような高度な文字数チェッカーを手に入れるためのGeminiにプロンプトを出すには私はどのようにプロンプトを書けば同等のコードを手に入れることが可能になるのでしょうか?

#!/usr/bin/env python3
# count_md_chars.py
# 追加インポート
import unicodedata
import argparse
import sys
from pathlib import Path
import re
import csv

MD_EXTS = {".md", ".markdown"}

def load_text(p: Path, encoding: str) -> str:
    with p.open("r", encoding=encoding, errors="replace") as f:
        return f.read()

def strip_front_matter(text: str) -> str:
    # 先頭のYAML Front Matter(--- ... ---)を除去
    if text.startswith("---\n"):
        m = re.search(r"^---\n.*?\n---\s*\n", text, re.DOTALL)
        if m:
            return text[m.end():]
    return text

def strip_markdown(text: str) -> str:
    t = text

    # コードフェンス ``` ``` と ~~~ ~~~ を除去(中身ごと)
    t = re.sub(r"```.*?```", "", t, flags=re.DOTALL)
    t = re.sub(r"~~~.*?~~~", "", t, flags=re.DOTALL)

    # インラインコード `code`
    t = re.sub(r"`[^`]*`", "", t)

    # 画像 ![alt](url) → alt だけ残す
    t = re.sub(r"!\[([^\]]*)\]\([^)]+\)", r"\1", t)

    # リンク [text](url) → text だけ残す
    t = re.sub(r"\[([^\]]+)\]\([^)]+\)", r"\1", t)

    # 参照式リンク [text][id] → text
    t = re.sub(r"\[([^\]]+)\]\[[^\]]*\]", r"\1", t)
    # 参照定義 [id]: url を除去
    t = re.sub(r"^\s*\[[^\]]+\]:\s+\S+.*$", "", t, flags=re.MULTILINE)

    # 見出し記号、引用記号、リスト記号を除去
    t = re.sub(r"^\s{0,3}#{1,6}\s*", "", t, flags=re.MULTILINE)       # # 見出し
    t = re.sub(r"^\s{0,3}>\s?", "", t, flags=re.MULTILINE)            # > 引用
    t = re.sub(r"^\s{0,3}([-*+]|(\d+\.))\s+", "", t, flags=re.MULTILINE)  # -,*,+,1. リスト

    # 強調記号 ** * __ _ ~~ を除去
    t = re.sub(r"(\*\*|\*|__|_|~~)", "", t)

    # テーブルの区切り | と :--- を弱めに除去(行に | が多い場合)
    def _strip_table_line(line: str) -> str:
        if "|" in line and re.search(r"\|.+\|", line):
            # セル区切りを単純にスペースに
            return re.sub(r"\s*\|\s*", " ", line)
        return line
    t = "\n".join(_strip_table_line(ln) for ln in t.splitlines())

    # HTMLタグを除去
    t = re.sub(r"<[^>]+>", "", t)

    # 横罫線と脚注定義の除去
    t = re.sub(r"^\s*[-*_]{3,}\s*$", "", t, flags=re.MULTILINE)       # --- *** ___ の水平線
    t = re.sub(r"^\s*\[\^[^\]]+\]:\s+.*$", "", t, flags=re.MULTILINE)  # 脚注定義 [^1]: ...

    return t


# 追加: 日本語のみ抽出する関数
JPN_LETTERS_RE = re.compile(r"[一-龯ぁ-んァ-ンー々〆ヶ]")  # 日本語"文字"
JPN_PUNCT_RE   = re.compile(r"[。、「」、!?]")            # よく使う和文句読点

def count_japanese_only(text: str, with_punct: bool) -> int:
    # まずZs/Zl/Zp(空白系)は無視するが、ここではどのみち拾わない
    letters = JPN_LETTERS_RE.findall(text)
    if with_punct:
        puncts = JPN_PUNCT_RE.findall(text)
        return len(letters) + len(puncts)
    else:
        return len(letters)


def count_chars(text: str, no_spaces: bool) -> int:
    if no_spaces:
        # 改行・スペース・タブなどを除外
        return len(re.sub(r"\s+", "", text))
    else:
        # 改行込みでカウント(PythonはUTF-8でのUnicode文字数)
        return len(text)

def iter_files(root: Path, recursive: bool, include_exts, include_globs, exclude_globs):
    paths = []
    it = root.rglob("*") if recursive else root.glob("*")
    for p in it:
        if not p.is_file():
            continue
        # 拡張子フィルタ
        if include_exts and p.suffix.lower() not in include_exts:
            continue
        # include パターン
        if include_globs and not any(p.match(g) for g in include_globs):
            continue
        # exclude パターン
        if exclude_globs and any(p.match(g) for g in exclude_globs):
            continue
        paths.append(p)
    return sorted(paths)

def main():
    ap = argparse.ArgumentParser(description="Markdownファイルの文字数集計ツール")
    ap.add_argument("folder", help="対象フォルダのパス")
    ap.add_argument("-r", "--recursive", action="store_true", help="サブフォルダも再帰的に処理")
    ap.add_argument("-e", "--ext", action="append", help="対象拡張子(例: -e .md -e .markdown)。未指定なら.md/.markdown", default=None)
    ap.add_argument("--encoding", default="utf-8", help="読み込みエンコーディング(既定: utf-8)")
    ap.add_argument("--strip-markdown", action="store_true", help="Markdown記法を除去してカウント")
    ap.add_argument("--no-spaces", action="store_true", help="空白・改行を除外してカウント")
    ap.add_argument("--ignore-front-matter", action="store_true", help="先頭のYAML Front Matterを無視")
    ap.add_argument("--include", action="append", help="globパターンで取り込み(例: --include '*/chapters/*.md')", default=None)
    ap.add_argument("--exclude", action="append", help="globパターンで除外(例: --exclude '*draft*')", default=None)
    ap.add_argument("--csv", help="結果をCSVに出力(パスを指定)")
    ap.add_argument("--jpn-only", action="store_true",
                    help="日本語の文字(漢字・ひらがな・カタカナ・長音・々〆ヶ)のみカウント")
    ap.add_argument("--jpn-with-punct", action="store_true",
                    help="日本語の文字+和文句読点(。、!?)をカウント")
    args = ap.parse_args()

    root = Path(args.folder)
    if not root.exists() or not root.is_dir():
        print(f"フォルダが見つからない: {root}", file=sys.stderr)
        sys.exit(1)

    include_exts = set(e.lower() for e in (args.ext or MD_EXTS))

    files = iter_files(
        root=root,
        recursive=args.recursive,
        include_exts=include_exts,
        include_globs=args.include,
        exclude_globs=args.exclude,
    )

    if not files:
        print("対象ファイルが見つからなかった。拡張子やパターンを見直してくれ。")
        sys.exit(0)

    rows = []
    total = 0

    for p in files:
        try:
            txt = load_text(p, args.encoding)
            if args.ignore_front_matter:
                txt = strip_front_matter(txt)
            if args.strip_markdown:
                txt = strip_markdown(txt)

            if args.jpn_only or args.jpn_with_punct:
                n = count_japanese_only(txt, with_punct=args.jpn_with_punct)
            else:
                n = count_chars(txt, args.no_spaces)
        except Exception as e:
            print(f"[WARN] 読み込み失敗: {p} ({e})", file=sys.stderr)
            continue

        rows.append((str(p), n))
        total += n

    # 表示
    print(f"対象ファイル数: {len(rows)}")
    print("=" * 60)
    for i, (path, n) in enumerate(rows, 1):
        filename = Path(path).name
        print(f"{i:2d}. {filename}")
        print(f"    文字数: {n:,}")
        print()
    print("=" * 60)
    print(f"合計文字数: {total:,}")    # CSV出力
    if args.csv:
        with open(args.csv, "w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["path", "chars"])
            for path, n in rows:
                w.writerow([path, n])
            w.writerow(["TOTAL", total])
        print(f"CSV出力: {args.csv}")

if __name__ == "__main__":
    main()

コードの仕様

主な機能

  1. Markdownファイルの文字数カウント

    • .md および .markdown ファイルを対象
    • 複数ファイルの一括処理が可能
  2. Markdown記法の処理

    • コードブロック(```、~~~)の除去
    • インラインコード(code)の除去
    • リンク記法の処理(URLを除去してテキストのみ残す)
    • 画像記法の処理(altテキストのみ残す)
    • 見出し、引用、リスト記号の除去
    • 強調記号(**、*、__、_、~~)の除去
    • HTMLタグの除去
    • テーブル記法の処理
  3. 前処理オプション

    • YAML Front Matterの除去
    • 空白・改行の除外カウント
    • Markdown記法の完全除去
  4. ファイル選択機能

    • 再帰的なサブフォルダ処理
    • 拡張子フィルタ
    • globパターンでの包含/除外指定
  5. 出力機能

    • コンソール表示(ファイル別 + 合計)
    • CSV出力対応
      Ran tool

使用例

現在のプロジェクト構造を見ると、以下のような使い方ができます

基本的な使用法

python count_md_chars.py text -r --strip-markdown --no-spaces


# 現在のフォルダ内のMarkdownファイルの文字数を集計
python count_md_chars.py .

# textフォルダ内のファイルを再帰的に処理
python count_md_chars.py text -r

# Markdown記法を除去して純粋なテキストのみカウント
python count_md_chars.py . --strip-markdown

# 空白・改行を除外してカウント
python count_md_chars.py . --no-spaces

# Front Matterを無視
python count_md_chars.py . --ignore-front-matter

高度な使用法

# 改善案フォルダのファイルのみ処理
python count_md_chars.py . --include "改善案/*.md"

#texttフォルダのファイルのみ処理
python count_md_chars.py . --include text/

# 特定のファイルを除外
python count_md_chars.py . --exclude "*draft*"

# 結果をCSVに出力
python count_md_chars.py . --csv result.csv

# 全オプションを組み合わせ
python count_md_chars.py . -r --strip-markdown --no-spaces --ignore-front-matter --csv detailed_count.csv

日本語“文字”ベース(句読点なし)

python count_md_chars.py ./contents -r --strip-markdown --jpn-only

日本語“文字”+句読点(読み感に寄せる)

python count_md_chars.py ./text -r --strip-markdown --jpn-with-punct

参考:これまでどおり(空白抜き)

python count_md_chars.py ./text -r --strip-markdown --no-spaces


はい、もうすでに、お前プログラム作っているじゃねえかというツッコミは野暮です。
私はとにかくこのようなコードを一瞬で作れるプロンプトが欲しかったのです。

するとこのようになりました。

Geminiが出したカスタムプロンプト

あなたは優秀なPythonエンジニアです。
ローカルフォルダ内にあるMarkdownファイルの文字数を、高度な条件で集計するCLIツールを作成してください。

【基本要件】
・対象: 指定したフォルダ内の .md または .markdown ファイル
・実行形式: コマンドラインから引数を渡して実行(argparseを使用すること)
・標準ライブラリ(pathlib, re, csv, argparseなど)のみで実装すること

【実装してほしい機能(オプション引数として実装)】
1. 探索オプション:
   - `-r`, `--recursive`: サブフォルダも再帰的に検索
   - `--include`, `--exclude`: globパターンでの包含・除外指定
   - `-e`, `--ext`: 対象拡張子の追加指定

2. カウントの除外・整形ルール:
   - `--ignore-front-matter`: 先頭のYAML Front Matter(---で囲まれた部分)を除外
   - `--strip-markdown`: Markdown記法(見出し、リンク、画像、コードブロック、太字など)を正規表現で除去して純粋なテキストにする
   - `--no-spaces`: 空白・改行を除外

3. 日本語特化モード:
   - `--jpn-only`: 日本語(漢字、ひらがな、カタカナ、長音符など)のみをカウント
   - `--jpn-with-punct`: 日本語+和文句読点(。、!?)のみをカウント

4. 出力オプション:
   - `--csv [ファイルパス]`: 集計結果を指定したCSVファイルに出力する

【出力形式(コンソール)】
エラー等で読み込めないファイルはスキップし、以下のようにカンマ区切りで見やすく出力してください。

対象ファイル数: X
============================================================
 1. ファイル名1.md
    文字数: 1,234

 2. ファイル名2.md
    文字数: 5,678
============================================================
合計文字数: 6,912

なるほど! 勉強になりました。
このようにすれば、恐らく高度な文字数チェッカーを手に入れることが可能かと思われます。

実際に出したプロンプトに関してはAIなので間違えることもあるかもしれませんので、検証してから実行してみましょう。

どうしても不安な方は、最初に書いた手堅いプロンプトを使うことで検証済みのコードが手に入ります。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?