Flaskで英単語を数えるアプリケーションを動かしてみた

2018.11.10

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

Python用のマイクロフレームワークFlaskを使って、簡単なアプリケーションを動かしてみたのでご紹介します。

Flaskのインストール

pip install -U Flask

やってみた

構成

├── application.py
├── static
│   └── css
│       └── bootstrap.min.css
└── templates
    └── main.html

英単語と数字をカウントするプログラム

テキストを受け取ると、英単語と数字をカウントする内容のアプリケーションです。

application.py

from flask import Flask, render_template, request
import re

app = Flask(__name__)


def count_word(text):

    words = re.findall(r'[a-z0-9\\’\\\']+', text.lower())

    return len(words)


@app.route('/', methods=['POST', 'GET'])
def home():

    total = ''

    if request.method == 'POST':
        text = request.form['text']
        total = count_word(text)

        return render_template('main.html', total=total, sentence=text)

    return render_template('main.html', total=total)


if __name__ == "__main__":
    app.run(debug=True)

ページ

Flaskはtemplatesフォルダからテンプレートを探しますので、templatesフォルダに配置します。また、CSSやJavaScriptはstaticフォルダ配下に配置します。今回はbootstrap.min.cssを以下のように置いています。

├── static
│   └── css
│       └── bootstrap.min.css

application.py では23,25行目のrender_templatemain.html を読み込んでいます。

main.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>English Word Count</title>

    <!-- Bootstrap -->
    <link href="/static/css/bootstrap.min.css" rel="stylesheet">
  </head>

  <body>
    <center>
    <h1>English Word Count</h1>
    <div class="form-group">
        <form method="POST" action="/">
                <textarea name="text" cols="100" rows="5" placeholder="I love pullups!">{{sentence}}</textarea><br>
                <input class="btn btn-primary" name="text" type="submit" value="Count Words">
        </form><br>
    <font size="5">{{total}} words</font>
    </center>

  </body>
</html>

ここで、変数を使用しています。

例)

<font size="5">{{total}} words</font>

{{total}}に、application.py で以下のようにして変数を渡しています。

return render_template('main.html', total=total)

実行

アプリケーションを起動

$ python application.py

アクセスする

http://127.0.0.1:5000

画像

画像

まとめ

Pyhonのウェブフレームワーク Flaskを触ってみました。興味がある方はFlaskのチュートリアルも試してみてください。

・日本語 Flask | クイックスタート

参考URL