きゃっとぐるーぶ

忘れてもいいようにメモを取っても、メモを取ったことを忘れる男の備忘録

クリップボードにある将棋倶楽部24の棋譜をファイルにする

将棋倶楽部24の自由対局室で対局すると棋譜が残らない。棋譜はコピーすれば保存できるが対局日、対局者名、そして勝敗を棋譜ファイル名に反映するのは手間だ。そこでそれらを勝手にやってくれるプログラムを書いた。

クリップボードは clipit を使用している。アクションコマンドを設定し、棋譜を容易に保存できるようにした。棋譜ファイルの保存場所は、pythonファイルのあるディレクトリになる。

アクション設定を画像のようにする

f:id:catgroove:20190531201324j:plain:w200

Ctrl + alt + a で保存が出来るようになる

f:id:catgroove:20190531201821p:plain:w150

import os
import sys
import pyperclip

from datetime import datetime
from pathlib import Path


clipboard = pyperclip.paste().splitlines()


def get_clipboard():
    rows = []
    for cb in clipboard:
        try:
            item, value = cb.split(':')
        except ValueError:
            continue
        else:
            rows.append(tuple(item, value))
    return rows


def which_winner():
    match_result = clipboard[-1]
    num, kif = match_result.split(' ')
    if '投了' in kif and int(num) % 2 == 0:
        # 先手が投了
        return 'ox'
    elif '投了' in kif and int(num) % 2 != 0:
        # 後手が投了
        return 'xo'

    if '引き分け' in kif:
        return '__'

    if '反則勝ち' in kif and int(num) % 2 == 0:
        #先手が反則
        return 'xo'
    elif '反則勝ち' in kif and int(num) % 2 != 0:
        #後手が反則
        return 'ox'


def to_split_timestap():
    for row in get_clipboard():
        if '開始日時' in row:
            timestamp = datetime.strptime(row[1], '%Y/%m/%d %H:%M:%S')
            timestamp = timestamp.strftime('%Y%m%d_%H%M%S')
    return timestamp


def to_split_sentename():
    for row in get_clipboard():
        if '先手' in row:
            _, sente_name = row
    return sente_name


def to_split_gotename():
    for row in get_clipboard():
        if '後手' in row:
            _, gote_name = row
    return gote_name


def compose_kif_info():
    return to_split_timestap(), to_split_sentename(), \
            which_winner(), to_split_gotename()


def create_filename():
    match_info = compose_kif_info()
    filename_fmt = '{}_{}_{}_{}.kif'
    return filename_fmt.format(*match_info)


def create_save_path():
    save_path = Path(os.path.dirname(__file__))
    return save_path / create_filename()


def save_kiffile():
    filepath = create_save_path()
    if not filepath.exists():
        with open(filepath, 'w', encoding='shift_jis') as _f:
            _f.write(pyperclip.paste())

def main():
    save_kiffile()


if __name__ == '__main__':
    main()

いちばんやさしい Python入門教室

いちばんやさしい Python入門教室

スラスラ読める Pythonふりがなプログラミング

スラスラ読める Pythonふりがなプログラミング