GraffitiNote

Pythonistaの情報系大学生がプログラミングやらDTMやらデザインやら

pythonで家計簿 その2

jsonで保存,表示させるところまで。
色々とオプションも動くようにしたけどまだ中途半端。
保存フォーマットの仕様を変更したので、
以前のファイルを新フォーマットに更新するhadbrf.pyも用意。

hadb.py

#Household Accounts Database
import json
import datetime
import locale

#データ格納ファイル
datafile = 'sample.json'

#初期辞書
initialdic = {'0': {'date':{'year':"0",'month':"0",'day':"0"},'item':{'kind':"0",'place':"0",'amount':"0"},'record':{'year':"0",'month':"0",'day':"0"}}}

#日付データ
thisdate = datetime.date.today()
thisyear,thismonth,thisday = str(thisdate).split('-')

#データ読み込み
def fileinput(filename,encoding):
    with open(filename,'r',encoding=encoding) as file:
        return(json.load(file))

#データ上書き
def fileoutput(filename,encoding,data):
    with open(filename,'w',encoding=encoding) as file:
        json.dump(data,file,sort_keys = True, indent = 4)

#年月日補完
def DatetimeCompletion(data):
    revdata = data[::-1]
    if len(revdata) == 3:
        revdata.append(thisday)
    if len(revdata) == 4:
        revdata.append(thismonth)
    if len(revdata) == 5:
        revdata.append(thisyear)
    completedata = revdata[::-1]
    return(completedata)

#総計
def TotalAmount():
    HADB = fileinput(datafile,'utf-8')
    index = [str(itr) for itr in range(len(HADB))]
    AllAmount = [int(HADB[itr]['item']['amount']) for itr in index]
    return(sum(AllAmount))

#データ抽出表示
def SearchDictionary():
    print("\nEnter: query\n")
    query = input()
    LineBreak()
    HADB = fileinput(datafile,'utf-8')
    index = [str(itr) for itr in range(len(HADB))]
    for itr in index:
        print(HADB[itr]['item'][query])

#データ変更
def ChangeDictionary():
    print("\nEnter: query origin replace")
    query,origin,replace = input().split()
    HADB = fileinput(datafile,'utf-8')
    index = [str(itr) for itr in range(len(HADB))]
    for itr in index:
        if HADB[itr]['item'][query] == origin:
            HADB[itr]['item'][query] = replace

    fileoutput(datafile,'utf-8',HADB)
    print("\ndata changed.")

#データ追加
def UpdateDictionary():
    #データ振り分け(年,月,日,種別,店名,金額)
    year,month,day,kind,place,amount = DatetimeCompletion(input().split())
    #日付,項目,記録日
    date = {'year':year,'month':month,'day':day}
    item = {'kind':kind,'place':place,'amount':amount}
    record = {'year':thisyear,'month':thismonth,'day':thisday}
    #追加する辞書
    newdata = {'date':date,'item':item,'record':record}
    #家計簿データベースに新しいデータを追加
    HADB = fileinput(datafile,'utf-8')
    numbering = str(len(HADB))
    HADB[numbering] = newdata
    #json形式で保存
    fileoutput(datafile,'utf-8',HADB)
    print("\ndata appended.")

#改行
def LineBreak():
    print("")

#実行文
while True:
    print("\nEnter: year month day kind place amount")
    print("Option: exit clear view search change\n")
    stdin = input() #標準入力
    if stdin == "exit": #終了
        LineBreak()
        break
    elif stdin == "clear": #データ初期化
        fileoutput(datafile,'utf-8',initialdic)
    elif stdin == "view": #データ一覧表示
        print(json.dumps(fileinput(datafile,'utf-8'),sort_keys = True, indent = 4))
        LineBreak()
        print("total amount =",TotalAmount())
    elif stdin == "search": #データ抽出表示
        SearchDictionary()
    elif stdin == "change": #データ変更
        ChangeDictionary()
    elif stdin == "sum": #総和を求める
        LineBreak()
        print(TotalAmount())
    else: #データ追加
        UpdateDictionary(stdin)

実行

$ python3 hadb.py

Enter: year month day kind place amount
Option: exit clear view search change

view
{
    "0": {
        "date": {
            "day": "0",
            "month": "0",
            "year": "0"
        },
        "item": {
            "amount": "0",
            "kind": "0",
            "place": "0"
        },
        "record": {
            "day": "0",
            "month": "0",
            "year": "0"
        }
    }
}

total amount = 571

Enter: year month day kind place amount
Option: exit clear view search change

exit  

$ 

hadbrf.py

import json

#データ変更ファイル
datafile = "sample.json"

# データ読み込み
def fileinput(filename,encoding):
    with open(filename,'r',encoding=encoding) as file:
        return(json.load(file))

#データ上書き
def fileoutput(filename,encoding,data):
    with open(filename,'w',encoding=encoding) as file:
        json.dump(data,file,sort_keys = True, indent = 4)

def HAReformat(oldHADB):
    newHADB = {'0': {'date':{'year':"0",'month':"0",'day':"0"},'item':{'kind':"0",'place':"0",'amount':"0"},'record':{'year':"0",'month':"0",'day':"0"}}}

    for i in range(len(oldHADB)):
        oldrecord = oldHADB[str(i)]
        olddata = oldrecord['data']

        year = olddata['year']
        month = olddata['month']
        day = olddata['day']
        date = {'year':year,'month':month,'day':day}

        amount = olddata['amount']
        kind = olddata['kind']
        place = olddata['place']
        item = {'kind':kind,'place':place,'amount':amount}

        thisyear = oldrecord['year']
        thismonth = oldrecord['month']
        thisday = oldrecord['day']
        record = {'year':thisyear,'month':thismonth,'day':thisday}

        newHADB[str(i)] = {'date':date,'item':item,'record':record}

    return(newHADB)

oldHADB = fileinput(datafile,'utf-8')
newHADB = HAReformat(oldHADB)
fileoutput(datafile,'utf-8',newHADB)