群馬県でPythonを使ったAIやシステムを開発しているファントム

Navigation
群馬県でPythonを使ったAIやシステムを開発しているファントム

群馬県でPythonを使ったAIやシステムを開発しているファントムです。企業の経営課題を最適なテクノロジーで解決します。テックブログではPythonを中心にプログラミングに役立つ情報を発信しています。

投稿を検索する


  • 株式会社ファントム コーポレートサイト

カテゴリー



  • AWS 16
  • Django 45
  • FastAPI 4
  • Flask 8
  • GCP 1
  • Information 37
  • Other 32
  • PHP 2
  • Python 93
  • Pythonista 3
  • Rust 1

タグ


Alembic API argparse Beautiful Soup black Channels charset CodeCommit datetime Django REST framework Docker enumerate f-string git GitHub glob Google Colaboratory i18n IAM Internship Jupyter Lambda Matplotlib Nginx OpenCV pandas PIL Pillow PostgreSQL PyCharm PyCon pyenv PyTorch Redis Rembg ReportLab requests S3 Sentry slack tqdm uWSGI venv Vue.js youtube
このサイトはreCAPTCHAによって保護されており、Googleのプライバシーポリシーと利用規約が適用されます。

© 2022 Fantom, Inc.

Hydra WordPress Theme by EckoThemes.

Published with WordPress.

Related Articles

Filter by Category

  • Python(93)
  • Django(45)
  • Information(37)
  • Other(32)
  • AWS(16)
  • Flask(8)
  • FastAPI(4)
  • Pythonista(3)
  • PHP(2)
  • GCP(1)
  • Rust(1)

Filter by Author

  • EIGHT (14)
  • hayai017 (2)
  • press (196)
Back to Latest Articles
Python

def文を用いて共通の処理を関数化する

以下の2つの記事の応用編です。 今回のポイントは以下の2つです。 ・気温の処理を関数化・Matplotlibで複数のグラフを出力 コードはGitHubリポジトリにあげています。 コード 出力結果 以下の様な気温と降水確率 […]

Posted on 15th 7月 2019 by press

Python

Pythonistaを使って最高気温と最低気温をグラフ化

前回作った気象庁のサイトからBeautifulSoup4を使ってスクレイピングするプログラムの応用編として、今回はiOSアプリのPythonistaを使って最高気温と最低気温をグラフ化します。グラフ化にはMatplotl […]

Posted on 11th 7月 2019 by press

Python

気象庁の天気予報をBeautifulSoup4でスクレイピング

気象庁の天気予報をBeautifulSoup4でスクレイピングします。サンプルとして群馬県の週間天気予報(場所、日付、曜日、最高気温、最低気温)を取得します。 コードはGitHubリポジトリにあげています。 週間天気予報 […]

Posted on 10th 7月 2019 by press

Django

DjangoでSQLログを出力して確認する

DjangoでSQLログを出力して確認する方法です。SQLログをリアルタイムで出力して、どういうクエリがどのタイミングで実行されているのか確認できます。設定方法は簡単で、DEBUG = Trueになっている状態でsett […]

Posted on 6th 7月 2019 by press

Django

DockerのPostgreSQLコンテナのリストア

Dockerで動いているPostgreSQLにデータをリストアする方法です。書き出したPostgreSQLのdumpファイル(リストア用データ)はデスクトップに置いてあるという前提で進めます。 ディレクトリ構造 Dock […]

Posted on 4th 7月 2019 by press

Django

Djangoで502 Bad Gatewayが頻発した時に調べたこと

Djangoで開発中のWebアプリで特定のURLにアクセスした時だけ、502 Bad Gatewayが頻発する様になりました。NginxとuWSGIのログを見たらuWSGIのworkerが死んで復活してを繰り返しているこ […]

Posted on 2nd 7月 2019 by press

Django

Djangoでcould not connect to serverエラーが出たら

DjangoでデータベースにPostgreSQLを使ってる際に以下のエラーが出た時の対処方法です。 サーバーのPostgreSQLのディレクトリに移動します。VERSIONの部分はインストールされているバージョンを入力し […]

Posted on 28th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(3)

前回からの続きです。 チャンネルレイヤーを有効化 チャンネルレイヤーを使用するためにバックエンドにRedisを使用します。Redisを使用するためにDockerを起動します。 以下のコマンドを実行してRedisを起動しま […]

Posted on 26th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(2)

前回からの続きです。 ルームビューを作成 chat > templates > chat > room.htmlを作成します。 ルームビューを表示するためのviewを作成します。 ルームビューへのurl […]

Posted on 25th 6月 2019 by press

Django

DjangoとChannelsで簡単なチャットサーバーを構築(1)

こちらのチュートリアルと同じ内容です。https://channels.readthedocs.io/en/latest/tutorial/index.html 環境 Python 3.7.0Django 2.2.2ch […]

Posted on 22nd 6月 2019 by press

Python

Beautiful Soupでoptionタグのvalueを取得する

Beautiful Soupで以下のようなHTMLのoptionタグのvalueを取得する方法です。 optionタグのvalueの値を取得する方法 soup = soup.find_all('option')optio […]

Posted on 15th 6月 2019 by press

Django

Dockerを使ってDjangoとPostgreSQL環境を構築する方法

Dockerを使ってシンプルなDjangoとPostgreSQLの開発環境を構築する方法です。GitHubリポジトリをクローンして以下のコマンドを入力します。 1. Dockerイメージを作成 2. Djangoプロジェ […]

Posted on 8th 6月 2019 by press

Django

DjangoでダウンロードするCSVの文字コードを設定

以下のような、attachmentをつけて即ダウンロードが始まるシステムで、文字コードをShift-JISにする為にto_csv()の引数にencodingをShift-JISに設定しても、ダウンロードするとUTF-8で […]

Posted on 6th 6月 2019 by press

Django

That port is already in use.が表示された時の対処法

Djangoでrunserverコマンドを使って開発用サーバーを起動した時にError: That port is already in use.が表示された時の対処法です。 Error: That port is al […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像を合成する

Pillowを使って画像を合成する方法です。GitHubリポジトリ 上の2つの画像を合成して、下の画像を生成します。 Pillowのインストール バージョン確認 ディレクトリ構造 画像をリサイズ base_image = […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像をリサイズする

Pillowを使って画像をリサイズする方法です。GitHubリポジトリ Pillowのインストール バージョン確認 ディレクトリ構造 画像をリサイズ files = glob.glob('./images/*')imag […]

Posted on 22nd 5月 2019 by press

Python

Pillowを使って画像をクロッピングする

Pillowを使って画像をクロッピングする方法です。ソースコードはGitHubにあげています。 Pillowのインストール バージョン確認 ディレクトリ構造 画像をクロッピング files = glob.glob('./ […]

Posted on 21st 5月 2019 by press

Django

Djangoで開発をする際に仮想環境を構築する方法

Djangoで開発をする際にvenvを使って仮想環境を構築する方法です。pyenvがインストールされていてバージョンを切り替えできる状態を前提に進めます。 仮想環境について Pythonで開発していると開発環境では最新の […]

Posted on 20th 5月 2019 by press

Python

PythonistaでiPhoneから株価をスクレイピング

Pythonistaには多くのモジュールがプリインストールされていて、スクレイピングに必要なBeautifulSoupも初めから使える様になっています。そこで、今回はiOSアプリのPythonistaを使ってiPhone […]

Posted on 2nd 5月 2019 by press

Django

pandasで読み込んだCSVの値がNaNだったときの対処方法

DjangoのWEBプリケーションでCSVをpandasで読み込んでforで一行ずつループ処理をしたところ、毎回決まったところで決まったエラーが出たのでPyCharmのデバッグ機能を使って原因を調べた内容です。 プログラ […]

Posted on 28th 4月 2019 by press

View Latest Posts
Python

def文を用いて共通の処理を関数化する


press
def文を用いて共通の処理を関数化する
Posted on 15th 7月 2019 by press
2024年度 インターンシップ 募集開始

以下の2つの記事の応用編です。 今回のポイントは以下の2つです。


・気温の処理を関数化
・Matplotlibで複数のグラフを出力

コードはGitHubリポジトリにあげています。

気象庁の天気予報をBeautifulSoup4でスクレイピング
Pythonistaを使って最高気温と最低気温をグラフ化

コード

import datetime
import re
import urllib.request

import matplotlib.pyplot as plt
from bs4 import BeautifulSoup


def temp_generate(temps):
    temp_list = []

    for temp in temps:
        temp = temp.text

        if '最低' not in temp and '最高' not in temp:
            temp = temp.replace('\n|\t', '').replace('(', '{').replace(')', '}')
            temp = re.sub('{.*?}', '', temp)

            if '/' in temp:
                temp = None
            else:
                temp = int(temp)

            temp_list.append(temp)

    return temp_list


url = urllib.request.urlopen('https://www.jma.go.jp/jp/week/315.html')
soup = BeautifulSoup(url, 'lxml')

days = soup.find("table", {"id": "infotablefont"}).find_all("tr")[0].find_all("th")
rainy = soup.find("table", {"id": "infotablefont"}).find_all("tr")[2].find_all("td")
max_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[4].find_all("td")
min_temp = soup.find("table", {"id": "infotablefont"}).find_all("tr")[5].find_all("td")

day_list = []
for day in days:
    day = day.text

    if '日付' not in day:
        day_list.append(day[:-1])

hour = datetime.datetime.now().hour

rainy_list = []
for rain in rainy:
    rain = rain.text

    if '降水確率' not in rain:
        if '/' in rain:
            if 0 <= hour < 6:
                rain = rain.split('/')[0]
            elif 6 <= hour < 12:
                rain = rain.split('/')[1]
            elif 12 <= hour < 18:
                rain = rain.split('/')[2]
            elif 18 <= hour < 24:
                rain = rain.split('/')[3]
        else:
            pass

        rainy_list.append(int(rain))

maxtemp_list = temp_generate(max_temp)
mintemp_list = temp_generate(min_temp)

x = day_list
plt.subplot(2, 1, 1)
plt.plot(x, maxtemp_list, label='Max', color="red", marker="o")
plt.plot(x, mintemp_list, label='Min', color="blue", marker="o")
plt.title("Weekly weather")
plt.xlabel("Day")
plt.ylabel("Temp")
plt.legend()

plt.subplot(2, 1, 2)
plt.plot(x, rainy_list, marker="o")
plt.title("Rainy percent")
plt.ylabel("Percent")

plt.show()

出力結果

以下の様な気温と降水確率のグラフが表示されます。

気温と降水確率のグラフ
気温と降水確率のグラフ

解説

気温の処理の関数化

def temp_generate(temps):
    temp_list = []

    for temp in temps:
        temp = temp.text

        if '最低' not in temp and '最高' not in temp:
            temp = temp.replace('\n|\t', '').replace('(', '{').replace(')', '}')
            temp = re.sub('{.*?}', '', temp)

            if '/' in temp:
                temp = None
            else:
                temp = int(temp)

            temp_list.append(temp)

    return temp_list

最高気温と最低気温の処理を関数化した部分です。最高気温と最低気温はどちらも同じ処理なので関数化します。今回の気温を抜き出す様な処理は関数化することで、一度の記述で済むので記述量を減らせます。

Pythonの関数は以下の様に関数を定義します。

def 関数名():
    処理

def temp_generate(temps):
temp_generateという関数を作り、引数にはtempsを指定します。

return temp_list
temp_generate関数は作成した気温のリストを返します。

maxtemp_list = temp_generate(max_temp)
mintemp_list = temp_generate(min_temp)
取得した気温情報をtemp_generate関数に渡し、関数内で作成したリストを受け取ります。

降水確率の整形

hour = datetime.datetime.now().hour

rainy_list = []
for rain in rainy:
    rain = rain.text

    if '降水確率' not in rain:
        if '/' in rain:
            if 0 <= hour < 6:
                rain = rain.split('/')[0]
            elif 6 <= hour < 12:
                rain = rain.split('/')[1]
            elif 12 <= hour < 18:
                rain = rain.split('/')[2]
            elif 18 <= hour < 24:
                rain = rain.split('/')[3]
        else:
            pass

        rainy_list.append(int(rain))

直近の降水確率は時間帯毎に表示されているので、現在時刻から適切な降水確率を抜き出します。

hour = datetime.datetime.now().hour
現在の時間(時のみ)を取得します

rain = rain.split('/')[0]
表示されている数値は/で区切られているので、/の前後の位置を指定して取得します。

複数のグラフを出力

x = day_list
plt.subplot(2, 1, 1)
plt.plot(x, maxtemp_list, label='Max', color="red", marker="o")
plt.plot(x, mintemp_list, label='Min', color="blue", marker="o")
plt.title("Weekly weather")
plt.xlabel("Day")
plt.ylabel("Temp")
plt.legend()

plt.subplot(2, 1, 2)
plt.plot(x, rainy_list, marker="o")
plt.title("Rainy percent")
plt.ylabel("Percent")

plt.show()

plt.subplot(2, 1, 1)
plt.subplot(2, 1, 2)
2つのグラフを縦に並べて出力します。

ファントムYouTubeチャンネル

株式会社ファントムへのお問い合わせ

群馬県でPythonを使ったAIやソフトウェアを開発している株式会社ファントムが運営しています。




    press
    • Beautiful Soup
    • Matplotlib
    • Share Article:
    • Twitter
    • Facebook
    • Pinterest
    • LinkedIn
    • Reddit
    Show Comments (0)

    Comments

    Cancel Reply

    コメントを投稿するにはログインしてください。

    Related Articles

    Django

    Djangoでカスタムコマンドを作り実行する

    DjangoでWEBアプリケーションを開発していてデータベースの集計などをバッチ処理したいときに、カスタムコマンドを作り実行する方法です。 今回はサンプルとしてmycommandアプリケーションを作成するので以下のコマン […]

    Posted on 24th 4月 2019 by press
    Django

    DjangoでQuerySetをpandasのDataFrameに変換する

    DjangoでQuerySetで取得したデータをそのままpandasのDataFrameに変換する方法です。データを成形する必要がないときや、とりあえず全件CSV化したいときなどに便利な方法です。

    Posted on 1st 4月 2019 by press