0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

残プロ 第-9回 ~6回から8回のプログラムを組み込む~

Last updated at Posted at 2021-06-10

各回の簡単なまとめ

それぞれの回の詳しいまとめは日曜日の第-12回でやります!

第6回 pandasを使ってcsvファイルの読み込み・書き込み.
第7回 reを使って正規表現による文字列の分割.
第8回 datetime, calendarを使って文字列を日付へ変換.次の第N曜日を計算.

あまり利用モジュールは増やしたくないんですが日に日に増えていってますね...

タスク管理用に組み込み

.csv

name:タスク名
deadline_date, deadline_time:期限(日),期限(時間)
isRoutine:習慣の場合は日数,又は既定の文章で指定 ["Every"や"Second"等の頻度? + "Monday"や"Sunday"等の曜日]
priority:重要度

となっています.時間部分についてはまだ未実装です.

csv_example.png

直貼りが一番分かりやすいですね!

.py

トークンはmytoken.pyにTOKEN="発行されたトークン"として保存しています.毎回編集するのが面倒なので.

TaskNotify.py
import requests
import datetime
import calendar
import re
import pandas as pd
from mytoken import TOKEN

class Task:
	def __init__(self, name, date, priority):
		self.name = name
		self.date = date
		self.priority = priority
		self.sentence = "{}まで残り{}日\n".format(name, abs(self.date-today).days)


def str2date(str_list):
    date_list = []
    for s in str_list:
        frequency = s[0]
        weekday = s[1]
        if frequency == "Every":
            if weekday == "Day":
                date = today
            else:
                delta = weekday_list.index(weekday) - today.weekday()
                if delta < 0:
                    delta += 7
                date = today + datetime.timedelta(days=delta)
        else:
            nth = frequency_list.index(frequency) + 1
            weekday_first, _ = calendar.monthrange(year=today.year, month=today.month)
            day = 7 * (nth-1) + (weekday_list.index(weekday) - weekday_first) % 7 + 1
            if day >= today.day:
               delta = day - today.day
               date = today + datetime.timedelta(days=delta)
            else:
                weekday_first, _ = calendar.monthrange(year=today.year, month=today.month+1)
                day = 7 * (nth-1) + (weekday_list.index(weekday) - weekday_first) % 7 + 1
                date = datetime.date(year=today.year, month=today.month+1, day=1) + datetime.timedelta(days=day-1)
        date_list.append(date)
    return date_list


def separateStr(string):
    separated_comma = string.split(',')
    separated_upper = []
    for s in separated_comma:
        separated_upper.append(re.findall('[A-Z][a-z]+', s))
    return separated_upper


def loadTasks(path_csv):
	csv_tasks = pd.read_csv(path_csv, encoding='shift-jis')
	list_tasks =[[] for _ in range(len(priority_list)+1)]
	for row in csv_tasks.itertuples():
		date = datetime.datetime.strptime(row.deadline_date, '%Y年%m月%d日').date()
		if type(row.isRoutine) is not float:
			try:
				routine = int(row.isRoutine)
				if date < today:
					date += datetime.timedelta(days=routine-1)
			except ValueError:
				if type(row.isRoutine) is str:
					str_list = separateStr(row.isRoutine)
					date_list = str2date(str_list)
					date = min(date_list)
			csv_tasks.at[row[0], 'deadline_date'] = date.strftime('%Y年%m月%d日')
		if type(row.priority) is str:
			list_tasks[priority_list.index(row.priority)].append(Task(row.name, date, row.priority))
		else:
			list_tasks[-1].append(Task(row.name, date, row.priority))
	csv_tasks.to_csv(path_csv, encoding='shift-jis', index=False)
	return list_tasks


def createMessage(list_tasks):
	sentences = "\n"
	for i in range(len(priority_list)):
		sentences += "===Priority:{}===\n".format(priority_list[i])
		for t in list_tasks[i]:
			if t.date >= today:
				sentences += t.sentence
	sentences += "===Routine===\n"
	for t in list_tasks[-1]:
		sentences += t.sentence
	return sentences


if __name__ == '__main__':
	frequency_list = ['First', 'Second', 'Third', 'Fourth']
	weekday_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
	priority_list = ['high', 'mid', 'low']
	today = datetime.date.today()

	list_tasks = loadTasks("tasks.csv")

	message_dict = {'message': createMessage(list_tasks)}

	url = 'https://notify-api.line.me/api/notify'
	TOKEN_dict = {'Authorization': 'Bearer ' + TOKEN}

	requests.post(url, headers=TOKEN_dict, data=message_dict)

LINE画面(実行結果)

talkroom_9.png

次回 第-10回は

LINE通知画面を工夫しようということで,絵文字や画像,スタンプなんかを使ってみます.

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?