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?

[streamlit×python]文字数カウントwebアプリケーションを作成してみた

Posted at

はじめに

Streamlitを使えば、Pythonで簡単にWebアプリケーションを作成できます。今回は「文字数カウント」という実用的なWebアプリをStreamlitで作成し、その作成過程を紹介します。 データサイエンスや機械学習のプロトタイプだけでなく、ちょっとしたツールもすぐにWebアプリ化できるStreamlitの魅力をぜひ体験してみてください。


利用したツール

  • Python(バージョン3.7以上推奨)
  • Streamlit(pip install streamlitでインストール)
  • テキストエディタ(VSCode、PyCharmなど)

実際に出来上がったもの

webアプリはこちらからご覧いただけます。


コード解説

word_count.py
import streamlit as st

def main():
    # アプリケーションのタイトルを設定
    st.set_page_config(page_title="文字数カウント", layout="centered")
    st.title("文字数カウントアプリ")

    st.write("テキストを入力し、「カウント」ボタンを押してください。")

    # ユーザーがテキストを入力するためのテキストエリア
    # heightを調整して、より多くのテキストを表示できるようにします
    user_input = st.text_area("ここにテキストを入力...", height=250)

    # カウントを実行するためのボタン
    if st.button("カウント"):
        # 入力されたテキストが空でない場合にのみカウントを表示
        if user_input:
            # 文字数をカウント (スペースや改行も含む)
            char_count = len(user_input)

            # スペースを除いた文字数をカウント
            char_count_no_spaces = len(user_input.replace(" ", "").replace("\n", ""))

            # 単語数をカウント (空白文字で区切る)
            # 空白文字のみの入力に対応するため、strip()で前後の空白を削除してから分割
            word_count = len(user_input.split()) if user_input.strip() else 0

            # 行数をカウント (改行コードで区切る)
            # 最後の行が空の場合でもカウントされるように、splitlines()を使用
            line_count = len(user_input.splitlines())

            st.subheader("カウント結果:")
            st.metric(label="文字数 (スペース・改行含む)", value=char_count)
            st.metric(label="文字数 (スペース・改行除く)", value=char_count_no_spaces)
            st.metric(label="単語数", value=word_count)
            st.metric(label="行数", value=line_count)
        else:
            st.warning("カウントするテキストが入力されていません。")
    else:
        # ボタンが押されていない初期状態、またはテキストが入力されていない場合に表示
        st.info("テキストを入力し、「カウント」ボタンを押してください。")

if __name__ == "__main__":
    main()

ポイント解説

  • st.set_page_config:ページタイトルやレイアウトを設定します。
  • st.title/st.write:見出しや説明文を表示します。
  • st.text_area:テキスト入力エリアを作成します(heightで高さ調整可能)。
  • st.button:ボタンを作成し、クリック時に処理を実行します。
  • st.metric:カウント結果をわかりやすく表示します。
  • 文字数・単語数・行数のカウント:Python標準の関数を使って、入力テキストの各種カウントを行います。

まとめ

Streamlitを使えば、Pythonの知識だけで簡単にWebアプリケーションを作成でき、すぐに公開・共有できるのが大きな魅力です。 今回作成した「文字数カウントアプリ」は、ブログ記事やレポートの文字数チェックなど、日常のさまざまな場面で活用できます。 Streamlitは他にもデータ可視化や機械学習モデルのデモなど、幅広い用途に応用できるので、ぜひ挑戦してみてください!

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?