Python+Excel 华尔街的一股清流

一.人生苦短,学点Python

如果你把衣服和裤子按照左边衣服,右边裤子,每次从最新的一套衣裤中间进行插入的话,那么每次拿,只要取出最左边的衣服和最右边的裤子即可,这是最省心的整理衣服的方式之一。同理,你也可以试着把你手机里的所有 app 放进一个文件夹里,最上排的几行 app 和最下排的几行 app分别代表你的搜索优先级,这样归类你最关注的 app 点开就有,次之的话得快速下滑到底部,最后实在不行的话,慢慢上翻的同时你会考虑要不要清理一些 app ,所以此举一举两得。

好像扯远了_(:з」∠)_今天呢要给大家讲一讲什么是自由意志…啊不…介绍一款量身定做的财务管理系统——旺财系统,废话不多说,下面是数据的设计原理,咱们直接上图吧:

在这里插入图片描述
在这里插入图片描述老一套,咱们Python Excel不分家,数据库还是用Excel来整,创建和首页内容咱们就先略过了哈。

在这里插入图片描述
income:收入,好多人这一辈子也只有税后收入这一种收入,作为固定劳动所得,这里的 税后收入 是财务管理的基础。

在这里插入图片描述
expend:支出,住房方式 包括了 ,选择 住 的话,后续在计算资金管理的时候将不考虑 住房 下的金额到底是多少了,如果是 租 的话,目前的算法是按照最低季付的方式进行计算,即最终银行卡余额至少保有三个月的房租才能进行财务管理,这样做可以降低你的未来的财务风险,预支 包括了信贷以及额外消费,这里的项都算作是固定支出。

在这里插入图片描述
在这里插入图片描述
budget:预算,预算里目前只有差旅的额外支出,以及兼职等额外收入,这里支持多行多样的预算方式,可将 赤黑字 下所有的预算结果合并纳入管理余额的计算中。

在这里插入图片描述investment:投资型管理,按照余额的梯度根据项目的投资比例进行管理,因为没有建立数学模型,这里只是粗放地预估了后期的回报。

在这里插入图片描述surplus:盈余型管理,和投资型管理模型一样,只是这里模型项的内容有所不同罢了。

在这里插入图片描述accuracy:精度,在财务管理的时候,最要紧的不是阈值,而是你的财务还差两块的时候,就是进不了投资型管理的模型(是不是和录取分数线很像(手动滑稽一下)),系统算法默认采用 精度向下 ,在做模型选用判断的是时候采用的公式是:最终余额 = 余额+下精度×修正因子/100,但是实际财务管理的时候,计算的还是判断前的余额。

二.需求是第一生产动力

1.主线任务:财务管理模型选择的最终判断:0~盈余梯度1、盈余梯度1~盈余梯度2…盈余梯度n~投资梯度1…投资梯度n-1~投资梯度n
2.修仙任务:手动选择财务管理模型,并解释模型未来回报的走向(自己对自己进行大数据分析)。
3.渡劫任务:爬取互联网可信信息(国家政治、产业发展、民生生活、股市行情),建立数学模型,结合分析目前主流的理财产品,自动推荐优质的股票、基金、期货、债券的理财产品等。

三.小舟从此逝,代码寄余生

二话不说先来个大纲,为了迎合主题,我特意站在了人生这个体宏观角度去理解财务之于人生的重要性和地位,并驾齐驱的当然要数健康了,至于健康和财务之间和 life 之间的关系我们后面慢慢叙说。

目录大纲
在这里插入图片描述
目前大致就这样子啦,以后的每个项目应该也只增不减的来用这个工程模型了,不过到了后期项目多了,或初创了 人生管理大系统 之后,有些目录还是要脱离出小项目并形成独立的目录,比如类和方法,这一点和我们的细胞与我们的关系有些相似,原来我们只是三两种细胞集合的特殊功能的生物,最后慢慢发展成为人的个体,而那削微有些变化的两三种细胞的集合反而成为了我们的器官或者功能。

Tool.py : 启动文件

# coding: utf-8

# 导入:   系统模块
import sys, os


# 导入:   私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from program.application.deep_handling import *
from program.application.data_handling import *
from program.system.file import *


# 定义全局变量
filePath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/basic/资金管理数据总表(月账单).xlsx'
fileBackuppath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/backup/basic/资金管理数据总表(月账单).xlsx'
dataPath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/generate/finance_data.py'
dataBackuppath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/backup/generate/finance_data.py'
funcName = '资产管理系统'


# 函数:   资产管理工具
# 传入:   无
# 返回:   无
def tool_main():
    # 打印当前路径
    # str=sys.argv
    # print(str)
    while True:
        # 判断并执行data处理文件
        if data_handling_main(filePath, dataPath):
            # 判断并执行Excel文件的备份
            if file_backup(filePath,fileBackuppath):
                deep_handling_main(filePath,funcName)
            else:
                print('文件备份失败,源文件不存在或路径有误!错误:file_backup')
        else:
            print('程序有误!错误:tool_main')
        print_restart_tool()
        while True:
            try:
                if int(input_yes_or_no.count) < 5:
                    judge = input_yes_or_no()
                    if judge == 'y':
                        pass
                        break
                    elif judge == 'n' or judge == 'exit':
                        print_function_close(funcName)
                        sys.exit()
                    else:
                        pass
                else:
                    print_input_limited_5()
                break
            except Exception as err:
                topString, middleString, _ = string_parentheses(pprint.pformat(err))
                if topString == 'InputError':
                    print(middleString)
                elif topString == 'RequestExit':
                    sys.exit(middleString)
                else:
                    sys.exit('一条野生异常需要处理......错误:revise_balance_data......描述:' + pprint.pformat(err))


if __name__ == '__main__':
    tool_main()
    pass

导入模块的语句就不说,tool_main() 里主要就是循环判断保持程序的生命周期,然后调用执行 data_handling_main()进行数据的处理,特别是修改数据文件之后,重新处理数据很重要。file_backup() 文件备份,写备份的时候是后面 deep_handling_main() 里有个bug,不知道是不是计算机运算竞争的原因,这里增加备份,可以让数据处理的写先执行,而后面的深度处理的读后执行。

data_handling_main() : 数据处理程序

	# coding:utf-8
	
	
	# 导入:   系统模块
	import sys, os, openpyxl, re, pprint, collections
	from openpyxl.utils import get_column_letter
	from collections import defaultdict
	
	
	# 导入:   私有模块
	# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
	from program.system.file import *
	from class_object.exception import *
	
	
	# 定义全局变量
	dataString = '# coding:utf-8\n\n'
	dataDict = collections.OrderedDict()
	homepageList = []
	# 列表内容主要为通过Excel公式得出的数据,结构:[坐标01,坐标02......]
	excelOperationlist = []
	
	
	# 函数:   程序入口
	# 传入:   filepath = Excel文件路径    datapath = 数据文件路径
	# 返回:   (返回值在子函数中,返回bool值)
	def data_handling_main(filepath, datapath):
	    while True:
	        try:
	            return data_arrangement(file_read_workbook(filepath),filepath, datapath)
	        except Exception as err:
	            topString, middleString, _ = string_parentheses(pprint.pformat(err))
	            if topString == 'InputError':
	                print(middleString)
	            elif topString == 'RequestExit':
	                sys.exit(middleString)
	            else:
	                sys.exit('一条野生异常需要处理......错误:data_handling_main......描述:' + pprint.pformat(err))
	
	
	# 函数:   数据整合
	# 传入:   wb = Excel文件句柄   datapath = 数据文件的路径
	# 返回:   True = bool值
	def data_arrangement(wb,filepath, datapath):
	    sheetlist, string = file_sheet_title_to_list_and_string(wb, True)
	    # 跳过'首页'的循环
	    for i in range(len(sheetlist)):
	        for row in range(1, wb[sheetlist[i]].max_row + 1):
	            if wb[sheetlist[i]].max_row > 1:
	                for col in range(1, wb[sheetlist[i]].max_column + 1):
	                    colstr = get_column_letter(col)
	                    # 如果为首页
	                    if i == 0:
	                        if wb[sheetlist[i]][colstr + str(row)].value is not None:
	                            dataDict.setdefault(colstr + str(row), []).append(wb[sheetlist[i]][colstr + str(row)].value)
	                        else:
	                            # 首页内容?填充
	                            pass
	                    else:
	                        # sheet第一行
	                        if row == 1:
	                            # 内容为空
	                            if wb[sheetlist[i]][colstr + '1'].value is None:
	                                raise RequestExit(sheetlist[i] + '页面中,表头不为空!请查看修改!错误:data_arrangement')
	                            else:
	                                dataDict.setdefault(wb[sheetlist[i]][colstr + '1'].value, []).append(colstr + str(row))
	                                # sheet第一行最后一列
	                                if col == wb[sheetlist[i]].max_column:
	                                    excelOperationlist.append(wb[sheetlist[i]][colstr + '1'].value)
	                                else:
	                                    pass
	                        else:
	                            if wb[sheetlist[i]][colstr + str(row)].value is None:
	                                pass
	                                raise RequestExit(sheetlist[i] + '页面中,正文数据缺失!请查看修改!错误:data_arrangement')
	                            else:
	                                pass
	                            dataDict.setdefault(wb[sheetlist[i]][colstr + '1'].value, []).append(colstr + str(row))
	
	            else:
	                raise RequestExit(sheetlist[i] + '页面中,正文数据缺失!请查看修改!错误:data_arrangement')
	        string = string + sheetlist[i] + '=' + string_ordereddict_to_dict(dataDict) + '\n\n'
	        dataDict.clear()
	        # 单页调试
	        # break
	    file_write_common(datapath, dataString + string + string_list_to_string_01(excelOperationlist))
	    return True
	
	
	if __name__ == '__main__':
	    filePath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/basic/资金管理数据总表(月账单).xlsx'
	    dataPath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/generate/finance_data.py'
	    data_handling_main(filePath, dataPath)

将Excel中的数据按照设计需求进行抽取并存储。

finance_data.py : 生成的数据文件

# coding:utf-8

sheetListdata=['homepage', 'income', 'expend', 'budget', 'investment', 'surplus', 'accuracy']

homepage={'A1':['资产管理数据总表内容说明:'],'D2':['income:月收入表'],'D5':['expend:月支出表'],'A8':['investment:可流动收入投资占比表'],'D8':['wave:额外收支'],'A11':['surplus:月结余额投资占比表'],'F11':['请按时查看每月银行卡余额,并做好理财管理哟!!!'],}

income={'税后收入':['A1', 'A2'],'总收入':['B1', 'B2'],}

expend={'住房方式':['A1', 'A2'],'住房':['B1', 'B2'],'出行':['C1', 'C2'],'餐饮':['D1', 'D2'],'杂项':['E1', 'E2'],'预支':['F1', 'F2'],'总支出':['G1', 'G2'],}

budget={'支出方式':['A1', 'A2'],'额外支出':['B1', 'B2'],'收入方式':['C1', 'C2'],'额外收入':['D1', 'D2'],'赤黑字':['E1', 'E2'],}

investment={'管理余额':['A1', 'A2', 'A3', 'A4'],'产业投资':['B1', 'B2', 'B3', 'B4'],'父母养老':['C1', 'C2', 'C3', 'C4'],'子女教育':['D1', 'D2', 'D3', 'D4'],'疾病保养':['E1', 'E2', 'E3', 'E4'],'环游世界':['F1', 'F2', 'F3', 'F4'],'个人教育':['G1', 'G2', 'G3', 'G4'],'理财投资':['H1', 'H2', 'H3', 'H4'],'比例':['I1', 'I2', 'I3', 'I4'],}

surplus={'月结余额':['A1', 'A2', 'A3'],'产业投资':['B1', 'B2', 'B3'],'父母养老':['C1', 'C2', 'C3'],'子女教育':['D1', 'D2', 'D3'],'环游世界':['E1', 'E2', 'E3'],'个人教育':['F1', 'F2', 'F3'],'理财投资':['G1', 'G2', 'G3'],'备用金':['H1', 'H2', 'H3'],'比例':['I1', 'I2', 'I3'],}

accuracy={'精度向下':['A1', 'A2'],'精度向上':['B1', 'B2'],'修正因子':['C1', 'C2'],}

operationListdata=['总收入', '总支出', '赤黑字', '比例', '比例', '修正因子']

deep_handling_main() : 深度处理程序

# coding:utf-8


# 导入:   系统模块
import os, win32api, math, sys
from prettytable import PrettyTable
from prettytable import PLAIN_COLUMNS

# 导入:   私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from program.system.file import *
from program.system.input import *
from data.generate.finance_data import *
from data.generate.finance_auxiliary import *
from program.system.list import *
from class_object.count_callback import *


# 函数:   程序入口
# 传入:   filepath = Excel文件路径   funcname = 功能函数名字
# 返回:   无
def deep_handling_main(filepath, funcname):
    # 函数bug:函数的执行和data文件的读取会形成?竞争关系,必须两次执行Tool.py主程序才能避免错误,目前通过文件备份避免
    pass
    while True:
        try:
            # print_function_open(funcname)
            wbData = file_read_workbook(filepath)
            judge_data_correct(wbData)
            # print_finance_Initialization(funcname,homepage)
            display_current_information(wbData)
            revise_balance_data(filepath, wbData, calc_balance(wbData), funcname)
            break
        except Exception as err:
            topString, middleString, _ = string_parentheses(pprint.pformat(err))
            if topString == 'InputError':
                print(middleString)
            elif topString == 'RequestExit':
                sys.exit(middleString)
            else:
                sys.exit('一条野生异常需要处理......错误:finance_main......描述:' + pprint.pformat(err))


# 函数:   判断Excel文件和Data文件的数据是否完全对应正确
# 传入:   wb = Excel文件句柄
# 返回:   无
def judge_data_correct(wb):
    # 数据匹配有点完善
    pass
    if int(wb[sheetListdata[4]][investment[operationListdata[3]][len(investment[operationListdata[3]])-1]].value) == 100:
        if int(wb[sheetListdata[5]][surplus[operationListdata[4]][len(surplus[operationListdata[4]]) - 1]].value) == 100:
            if int(wb[sheetListdata[6]][accuracy[operationListdata[5]][len(accuracy[operationListdata[5]]) - 1]].value) < 100:
                pass
            else:
                raise RequestExit(print_reset(sheetListdata[6], '比例结果不为100!'))
        else:
            raise RequestExit(print_reset(sheetListdata[5], '比例结果不为100!'))
    else:
        raise RequestExit(print_reset(sheetListdata[4], '比例结果不为100!'))

# 函数:   显示目前正常收支和额外收支的情况
# 传入:   wb = Excel文件的句柄   dict = 数据字典   sheetName = 数据字典的变量名,值为字符串类型
# 返回:   无(打印制表)
def display_current_information(wb):
    print_plan_income_and_expend()
    make_income_expend_wave_plane(wb, income, string_varname_to_str(income))
    make_income_expend_wave_plane(wb, expend, string_varname_to_str(expend))
    make_income_expend_wave_plane(wb, budget, string_varname_to_str(budget))


# 函数:   将计划收支后的数据和额外收支的波动数据,通过制表的形式在屏幕上展现
# 传入:   wb = Excel文件句柄   dict = 字典:数据详见finance_data.py   sheetName = 字符串:传入dict对应的字典名称
# 返回:   无(打印制表)
def make_income_expend_wave_plane(wb, dict, sheetName):
    colValue = []
    table = PrettyTable()
    for k, v in dict.items():
        for i in range(1, len(v)):
            if wb[sheetName][v[i]].value is None:
                colValue.append('0')
            else:
                colValue.append(wb[sheetName][v[i]].value)
        # print(k,colValue)
        table.add_column(k, colValue)
        colValue = []
    # 无边框
    table.set_style(PLAIN_COLUMNS)
    # 左对齐
    table.align = 'l'
    print(table)


# 函数:   根据住房方式判断住房金额是否纳入计算正常收支和额外收支余额的范畴
# 传入:   wb = Excel文件句柄
# 返回:   balance = 收支余额
def calc_balance(wb):
    if wb[sheetListdata[2]][expend['住房方式'][1]].value == '住':
        balanceHouse = int(wb[sheetListdata[2]][expend[operationListdata[1]][1]].value) - int(wb[sheetListdata[2]][expend['住房'][1]].value)
    elif wb[sheetListdata[2]][expend['住房方式'][1]].value == '租':
        balanceHouse = int(wb[sheetListdata[2]][expend[operationListdata[1]][1]].value)
    else:
        raise RequestExit('Excel文件 '+ sheetListdata[2] +'\' 住房方式 \'下的数据有误!')
    # 遍历budget的预算支出方式
    for i in range(len(budget[operationListdata[2]])):
        balance = int(wb[sheetListdata[1]][income[operationListdata[0]][1]].value) - balanceHouse
        if i == 0:
            pass
        else:
            balance += int(wb[sheetListdata[3]][budget[operationListdata[2]][i]].value)
    print('\n' + '计算后可用余额:    {}'.format(balance))
    return balance


# 函数:  进行余额判断,分析管理模型
# 参数:  filepath = Excel文件路径   wb = Excel文件句柄   funcname = 功能函数名字
# 返回:  无
def revise_balance_data(filepath, wb, balance, funcname):
    pass
    investment_or_surplus_proportion_display(wb, balance)
    print_if_surplus()
    while True:
        try:
            if int(input_no_negative.count) < 5:
                figure = input_no_negative()
                investment_or_surplus_proportion_display(wb, str(deep_balance_count(wb,figure)))
            else:
                print_input_limited_5()
            break
        except Exception as err:
            topString, middleString, _ = string_parentheses(pprint.pformat(err))
            if topString == 'InputError':
                print(middleString)
            elif topString == 'RequestExit':
                sys.exit(middleString)
            else:
                sys.exit('一条野生异常需要处理...错误:revise_balance_data...描述:' + pprint.pformat(err))
    print_open_datafile()
    while True:
        try:
            if int(input_yes_or_no.count) < 5:
                judge = input_yes_or_no()
                if judge == 'y':
                    win32api.ShellExecute(0, 'open', filepath, '', '', 1)
                elif judge == 'exit':
                    print_function_close(funcname)
                    sys.exit()
                # judge = n
                else:
                    pass
            else:
                print_input_limited_5()
            break
        except Exception as err:
            topString, middleString, _ = string_parentheses(pprint.pformat(err))
            if topString == 'InputError':
                print(middleString)
            elif topString == 'RequestExit':
                sys.exit(middleString)
            else:
                sys.exit('一条野生异常需要处理......错误:revise_balance_data......描述:' + pprint.pformat(err))

# 函数:  根据租房付款方式对余额进行深度处理
# 参数:  wb = Excel文件句柄   balance = 管理余额
# 返回:  无
def deep_balance_count(wb,balance):
    # 算法完善:月、季度、半年、年
    pass
    if wb[sheetListdata[2]][expend['住房方式'][1]].value == '住':
        if int(wb[sheetListdata[2]][expend['住房'][1]].value) == 0:
            pass
            return balance
        else:
            balanceCorrect = int(balance) + int(wb[sheetListdata[2]][expend['住房'][1]].value)
            return balanceCorrect
    elif wb[sheetListdata[2]][expend['住房方式'][1]].value == '租':
        if int(wb[sheetListdata[2]][expend['住房'][1]].value) == 0:
            raise RequestExit('租房金额不能为零!')
        else:
            if int(balance) < int(wb[sheetListdata[5]][surplus['月结余额'][1]].value):
                print_guarantee_rent()
                return balance
                # raise RequestExit('已退出...')
            else:
                balanceCorrect = int(balance) - int(wb[sheetListdata[2]][expend['住房'][1]].value) * 3
                return balanceCorrect
    else:
        raise RequestExit('finance_data.py文件有误,无法与数据文件\'住房方式\'下的数据对应上!')


# 函数:  计划收支后的余额规划占比显示
# 参数:  wb = Excel文件句柄   balance = 管理余额
# 返回:  无
@CallingCounter
def investment_or_surplus_proportion_display(wb, balance):
    # 管理余额 金额等级
    thresholdInvestment, nameInvestemt = list_dict_break_down_01(wb, sheetListdata[4], investment)
    # 月结余额 金额等级
    thresholdSurplus, nameSurplus = list_dict_break_down_01(wb, sheetListdata[5], surplus)
    # 修正后的收支余额
    balanceCorrectdown = int(balance) + int(wb[sheetListdata[6]][accuracy['精度向下'][1]].value) * int(
        wb[sheetListdata[6]][accuracy['修正因子'][1]].value) / 100
    # 计划收支余额 小于 月结余额最小值
    if int(balanceCorrectdown) <= int(thresholdSurplus[0]):
        print_no_surplus(int(thresholdSurplus[0]) + int(wb[sheetListdata[2]][expend['住房'][1]].value)*3)
    else:
        # 管理余额的最小模型 < 月结余额的最大模型 + 1000
        if int(thresholdInvestment[0]) < int(thresholdSurplus[len(thresholdSurplus) - 1]) + 1000:
            raise RequestExit(print_reset(sheetListdata[4], '月结余额的最大值+1000 要小于 管理余额的最小值'))
        else:
            # 月结余额 只有一种模型
            if len(thresholdSurplus) == 1:
                # 月结余额模型 < 余额 < 管理余额的最低模型
                if int(thresholdSurplus[len(thresholdSurplus) - 1]) < int(balanceCorrectdown) <= int(
                        thresholdInvestment[0]):
                    # 采用 月结余额 的投资比例
                    make_investment_surplus_plane(wb, balance, surplus, sheetListdata[5], 2)
                else:
                    # 管理余额 只有一种模型
                    if len(thresholdInvestment) == 1:
                        # 采用 管理余额 的投资比例
                        make_investment_surplus_plane(wb, balance, surplus, sheetListdata[5], 2)
                    else:
                        # investment:管理余额模型循环
                        for i in range(len(thresholdInvestment)):
                            # 模型是否是最高模型
                            if i == len(thresholdInvestment) - 1:
                                # 管理余额 最高模型 < 余额
                                if int(thresholdInvestment[i]) <= int(balanceCorrectdown):
                                    # 采用 管理余额 的投资比例
                                    make_investment_surplus_plane(wb, balance, investment, sheetListdata[4], i + 1)
                                else:
                                    pass
                            else:
                                # 管理余额模型i < 余额 < 管理余额模型i+1
                                if int(thresholdInvestment[i]) < int(balanceCorrectdown) <= int(
                                        thresholdInvestment[i + 1]):
                                    # 采用 管理余额 的投资比例
                                    make_investment_surplus_plane(wb, balance, investment, sheetListdata[4], i + 1)
                                else:
                                    pass
            else:
                # surplus:月结余额模型循环
                for i in range(len(thresholdSurplus)):
                    # 模型是否是最高模型
                    if i == len(thresholdSurplus) - 1:
                        # 月结余额 最高模型 < 余额 < 管理余额 最低模型
                        if int(thresholdSurplus[i]) < int(balanceCorrectdown) <= int(thresholdInvestment[0]):
                            # 采用 管理余额 的投资比例
                            make_investment_surplus_plane(wb, balance, surplus, sheetListdata[5], i + 1)
                        else:
                            # investment:管理余额模型循环
                            for i in range(len(thresholdInvestment)):
                                # 模型是否是最高模型
                                if i == len(thresholdInvestment) - 1:
                                    # 管理余额 最高模型 < 余额
                                    if int(thresholdInvestment[i]) <= int(balanceCorrectdown):
                                        # 采用 管理余额 的投资比例
                                        make_investment_surplus_plane(wb, balance, investment, sheetListdata[4], i + 1)
                                    else:
                                        # 管理余额模型i < 余额 < 管理余额模型i+1
                                        if int(thresholdInvestment[i]) < int(balanceCorrectdown) <= int(
                                                thresholdInvestment[i + 1]):
                                            # 采用 管理余额 的投资比例
                                            make_investment_surplus_plane(wb, balance, investment, sheetListdata[4],
                                                                          i + 1)
                                        else:
                                            pass
                                else:
                                    # 管理余额模型i < 余额 < 管理余额模型i+1
                                    if int(thresholdInvestment[i]) < int(balanceCorrectdown) <= int(
                                            thresholdInvestment[i + 1]):
                                        # 采用 管理余额 的投资比例
                                        make_investment_surplus_plane(wb, balance, investment, sheetListdata[4], i + 1)
                                    else:
                                        pass
                    else:
                        # 管理余额模型i < 余额 < 管理余额模型i+1
                        if int(thresholdSurplus[i]) < int(balanceCorrectdown) <= int(
                                thresholdSurplus[i + 1]):
                            # 采用 管理余额 的投资比例
                            make_investment_surplus_plane(wb, balance, surplus, sheetListdata[5], i + 1)
                        else:
                            pass
    # # 调试上面逻辑打开
    # # 如果 investment_or_surplus_proportion_display 函数不止调用了 1 次
    # if int(investment_or_surplus_proportion_display.count) == 2:
    #     # 如果 make_investment_surplus_plane 函数被默认调用了 1 次
    #     if int(make_investment_surplus_plane.count) == 1:
    #         raise RecursionError('make_investment_surplus_plane函数未被调用,请查看investment_or_surplus_proportion_display函数中pass所在域中的逻辑!!!')
    #     else:
    #         pass
    # else:
    #     pass


# 函数:   将余额管理和月结余额的分成比例数据在屏幕上展现
# 传入:   wb = Excel文件句柄   principal = 计划收支余额   dict = 字典:数据详见finance_data.py   sheetName = 字符串:传入dict对应的字典名称
# 返回:   无(打印制表)
@CallingCounter
def make_investment_surplus_plane(wb, principal, dict, sheetName, ratiolocation):
    print_capital_management()
    colValue = []
    table = PrettyTable()
    count = 0
    for k, v in dict.items():
        if count == 0 or count == len(dict) - 1:
            pass
        else:
            for i in range(len(dict)):
                if i == 0 or i == len(dict) - 1:
                    pass
                else:
                    if wb[sheetName][v[ratiolocation]].value is None:
                        colValue.append('0')
                    else:
                        colValue.append(str(math.floor(int(principal) * int(wb[sheetName][v[ratiolocation]].value) / 100)))
                    break

            table.add_column(k, colValue)
            colValue = []
        count += 1
    # 无边框
    table.set_style(PLAIN_COLUMNS)
    # 左对齐
    table.align = 'l'
    print(table)


if __name__ == '__main__':
    filepath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/basic/资金管理数据总表(月账单).xlsx'
    funcName = '资产管理系统'
    deep_handling_main(filepath, funcName)

主要实现的功能,在前面章节一、二,以及Excel表格截图后面的话里都有写明了,代码注释也能帮到一部分,这里便不再赘述了。
剩余辅助的代码文件如下展示:

file.py : 文件 封装模块

# coding:utf-8


# 导入:   系统模块
import openpyxl,pprint,sys,os
from shutil import copyfile


# 导入:   私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from program.system.string import *
from program.system.print import *
from class_object.exception import *


# 函数:   文件正常读取
# 传入:   filepath = 文件路径
# 返回:   wbData = 文件句柄
def file_read_common(filepath):
    try:
        # print(filepath)
        wbData = openpyxl.load_workbook(filepath)
        # print_success()
        return wbData
    except Exception as err:
        topString, middleString, _ = string_parentheses(pprint.pformat(err))
        print(middleString)
        if topString == 'RequestExit':
            sys.exit(middleString)
        else:
            print_fail()
            raise RequestExit('路径有问题,文件读取失败!错误:file_read_common......描述:' + pprint.pformat(err))


# 函数:   文件正常写入
# 传入:   filepath = 文件路径   string = 写入内容
# 返回:   无
def file_write_common(filepath,string):
    try:
        outFile = open(filepath, 'w', encoding='utf-8')
        if string == '' or string is None:
            outFile.close()
            print_fail()
            raise RequestExit('写入内容为空,文件写入失败!错误:file_write_common')
        else:
            outFile.write(string)
            # print_success()
    except Exception as err:
        topString, middleString, _ = string_parentheses(pprint.pformat(err))
        if topString == 'RequestExit':
            sys.exit(middleString)
        else:
            print_fail()
            raise RequestExit('路径有问题,文件写入失败!错误:file_write_common......描述:' + pprint.pformat(err))


# 函数:   读取Excel工作簿
# 传入:   filepath = 文件路径
# 返回:   wbData = 文件句柄
def file_read_workbook(filepath):
    try:
        # print(filepath)
        wbData = openpyxl.load_workbook(filepath,data_only=True)
        return wbData
    except Exception as err:
        print_fail()
        raise RequestExit('代码路径有误或文件不存在!错误:file_read_workbook......描述:' + pprint.pformat(err))


# 函数:   获取Excel的所有sheet的名称
# 传入:   wbdata = Excel文件句柄   bool = 布尔值:传True则将sheet名称放入指定列表,传False则返回''
# 返回:   shList = 列表:含所有sheet名称   string = 字符串:内容为:'sheetListdata=[sheet01,sheet02......]' 或 ''
def file_sheet_title_to_list_and_string(wbdata,bool):
    shList=[]
    string = ''
    for sheet in wbdata:
        shList.append(sheet.title)
        # print(sheet.title)
    if bool:
        string = string + 'sheetListdata' + '=' + pprint.pformat(shList) + '\n\n'
    else:
        pass
    return shList,string


# 函数:   文件备份
# 传入:   source = 源文件路径(包含文件)   target = 目标文件路径(包含文件)
# 返回:   True = bool值
def file_backup(source,target):
    try:
        copyfile(source, target)
        # print_success()
    except Exception as err:
        topString, middleString, _ = string_parentheses(pprint.pformat(err))
        if topString == 'RequestExit':
            sys.exit(middleString)
        else:
            print_fail()
            raise RequestExit('文件写入失败!错误:file_backup......描述:' + pprint.pformat(err))
    return True


if __name__ == '__main__':
    filePath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/data/basic/资金管理数据总表(月账单).xlsx'
    dataPath = 'C:/Mr.lu/who to where/Life management/where life/Finance/finance management/datas/generate/finance_data.py'
    file_write_common(dataPath,'aa')
    file_read_common(filePath)
    pass

input.py : input 封装模块

# coding:utf-8


# 导入系统模块
import openpyxl,pprint,sys,os


# 导入私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from program.system.string import *
from program.system.print import *
from class_object.exception import *
from class_object.count_callback import *
from configure.yes_no_exit import judgeYesNoExit


# 函数:   输入判断:是、否、exit
# 传入:   无
# 返回:   str = y 或 n 或 exit   k = y 或 n 或 exit
@CallingCounter
def input_yes_or_no():
    str = input()
    for k,v in judgeYesNoExit.items():
        if str == k:
            return str
        else:
            for i in range(len(v)):
                if re.search(str,v[i],flags=re.I) is not None:
                    return k
                else:
                    pass
    raise InputError('输入有误,请重新输入:        (y/n)(exit退出)')


# 函数:   输入判断:0和正数
# 传入:   无
# 返回:   num = 非负数
@CallingCounter
def input_no_negative():
    num = input()
    if num == 'exit':
        raise RequestExit('已退出......')
    elif re.search(r'\D',num) is not None:
        raise InputError('输入有误,请重新输入:        (exit退出)')
    else:
        return num

list.py : list 封装模块

# coding:utf-8


# 导入系统模块
import openpyxl,pprint,sys,os


# 导入私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from program.system.string import *


# 函数:   将字典 dict = {X:[a,b,c]} 分解成 list01 = [X] list02 = [a,b,c]
# 传入:   dict = 字典
# 返回:   threshold = 列表:原来字典中的值   name = 列表:原来字典中的键
def list_dict_break_down_01(wb,sheetname,dict):
    name = []
    threshold = []
    for k, v in dict.items():
        for i in range(len(v)):
            if i == 0:
                name.append(wb[sheetname][dict[k][i]].value)
            else:
                threshold.append(wb[sheetname][dict[k][i]].value)
        break
    return threshold,name

print.py : print 封装模块

# coding:utf-8


# 导入:   系统模块
import sys,os,pprint


# 导入:   私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))


# sug:建议将表情入库并分类,最后随机数打印
# tips:如果表情符号非utf-8,则会报错

# 函数:   进入系统提示,打印数据信息
# 传入:   func = 字符串:系统名称   dict = 字典:包含列表,如 {'':[]}
# 返回:   无
def print_finance_Initialization(string,dict):
    for k,v in dict.items():
        print(v[0])


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_plan_income_and_expend():
    print('目前计划收支配置如下:')


# 函数:   打印提示信息
# 传入:   data = 计划收支余额
# 返回:   无
def print_plan_balance(data):
    print('计划余额为:{}'.format(data))


# 函数:   打印提示信息
# 传入:   sheetname = sheet名字   value = cell值   info = 字符串:提示信息
# 返回:   无
def print_reset(sheetname,info):
    print('请重新设置 {} 页的,提示信息:{}'.format(sheetname,info))


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_capital_management():
    print('\n~~ ̄▽ ̄~~秃噜秃噜')
    print('资金管理如下(计算方式:向下取整):')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_open_datafile():
    print('\n(〇o〇;)')
    print('是否需要打开数据文件进行修改?        (y/n)(exit退出)')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_input_limited_5():
    print('\n(〇o〇;)')
    print('输入超过5次......')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_restart_tool():
    print('\n(〇o〇;)')
    print('是否重新执行程序?        (y/n)(exit退出程序)')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_guarantee_rent():
    print('\n(〇o〇;)')
    print('请攒够季度房租再来吧!')


# 函数:   打印提示信息
# 传入:   string = 计划收支余额
# 返回:   无
def print_no_surplus(balance):
    print('\n(~ ̄▽ ̄)~[该吃吃,该喝喝,凡事别往心里搁!]')
    print('余额太少,攒够 {} 再来!'.format(balance))


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_if_surplus():
    print('\n(~ ̄▽ ̄)~[打劫!]')
    print('搜刮你的钱袋子,把你的余额交出来,快!             (exit退出程序)')


# 函数:   打印提示信息
# 传入:   funcname = 功能函数名称
# 返回:   无
def print_function_open(funcname):
    print('\n~~ ̄▽ ̄~~open')
    print('***' + funcname + '功能开启***')
    print('目前系统功能开发有待完善,自行判断余额中是否包含住房资金(〇o〇;)避免睡马路!')


# 函数:   打印提示信息
# 传入:   funcname = 功能函数名称
# 返回:   无
def print_function_close(funcname):
    print('请按时查看每月银行卡余额,并做好理财管理哟!!!')
    print('\n~~ ̄▽ ̄~~close')
    print('---' + funcname + '功能结束---')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_fail():
    print('\n(〇o〇;)')
    # print('***失败了***')


# 函数:   打印提示信息
# 传入:   无
# 返回:   无
def print_success():
    print('\n~~ ̄▽ ̄~~嘿')
    # print('*—*—*成功了*—*—*')


if __name__ == '__main__':
    pass

string.py : string 封装模块

# coding:utf-8

# 导入:   系统模块
import inspect,re,sys,os,pprint


# 导入:   私有模块
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))


# func:  取出字符串中最外层圆括号(包括中文的)内的字符串
# 参数:  string = 要切割的字符串
# 传入:  string = 切割字符串:如 ssa,n//2h1e)()as.sad>f,,qwmcma()wkql(laksdkl))))aa
# 返回:  startString = 最外层括号左边字符串:如 ssa,n//2h1e
#       middleString = 最外层括号内字符串:如 ()as.sad>f,,qwmcma()wkql(laksdkl)))
#       endingString = 最外层括号右边字符串:如 aa
def string_parentheses(string):
    num = []
    startString = ''
    middleString = ''
    endingString = ''
    for i in range(len(string)):
        if string[i] == '(' or string[i] == ')' or string[i] == '(' or string[i] == ')':
            num.append(i)
    for i in range(0, num[0]):
        startString = startString + string[i]
    for i in range(num[0] + 1, num[len(num) - 1]):
        middleString = middleString + string[i]
    for i in range(num[len(num) - 1] + 1, len(string)):
        endingString = endingString + string[i]
    return startString, middleString, endingString


# 函数:   清除字符串中的字符或字符串
# 传入:   string = 原字符串   dumpstring = 丢弃字符串
# 返回:   (调用replace(),返回值为替换后的字符串)
def string_dump(string,dumpstring):
    if re.search(dumpstring,string) is not None:
        return string.replace(dumpstring,'')
    else:
        raise RecursionError('传入的数据有误!错误:string_dump')


# 函数:   将ordereddict类型的字典转换成普通字典字符串
# 传入:   dict = 字典:经过排序之后的字典,如 dict = {} 无序    dict = collections.OrderedDict() 有序
# 返回:   string = 字符串:字典数据的拼接
def string_ordereddict_to_dict(dict):
    string=''
    for k, v in dict.items():
        string= string + pprint.pformat(k) + ':' + pprint.pformat(v) +','
    string='{'+string+'}'
    return string


# 函数:   遍历判断字符串中是否存在空格
# 传入:   string = 需要校验的字符串
# 返回:   True = bool值   False = bool值
def string_have_empty(string):
    for i in range(len(string)):
        if string[i-1] == ' ':
            return True
    return False


# 函数:   将列表内容拼接成字符串,风格为01
# 传入:   list = 列表:拼接的字符串数据
# 返回:   string = 拼接完成数据
def string_list_to_string_01(list):
    string = ''
    string = string + 'operationListdata' + '=' + pprint.pformat(list) + '\n\n'
    return string


# 函数:   变量名转换成字符串,tips:函数名在search函数中作为字符串,次函数的调用只能赋值一次,连续回调只返回第一个变量名
# 传入:   p = 任意参数:函数功能就是将入口参数的名称以字符串的方式取出
# 返回:   m.group(1) = p:调用函数时传入的参数名称
def string_varname_to_str(p):
    for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
        m = re.search(r'\bstring_varname_to_str\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
        if m:
            return m.group(1)


if __name__ == '__main__':
    pass
    dict={'zz':'2','ss':'4','df':'rrr'}
    print(string_ordereddict_to_dict(dict))

count_callback.py : 这是一个类文件,功能很有意思,可以记录被他提前标记@过的函数被调用数,本来还想结合多线程弄个计时器,简单实现5分钟内不超过5次输入则不退出的功能的,但考虑项目周期(此处应该有滑稽)…

# coding:utf-8


# 类:统计函数被调用次数的方法
class CallingCounter(object):
    def __init__ (self, func):
        self.func = func
        self.count = 0

    def __call__ (self, *args, **kwargs):
        self.count += 1
        return self.func(*args, **kwargs)

这个是我无意中瞥了一眼拿来用的,类和方法得有时间静下来才能学,包括后面的进程、线程、协程等。

exception.py :错误类型类文件,是之前项目的老一套移植过来的

# coding:utf-8


# 类:input输入错误,打印错误类型方法
class InputError(Exception):
    def __init__(self, message):
        self.message = message

    def fail_information(self):
        print(self.message)


# 类:请求退出,打印错误类型方法
class RequestExit(Exception):
    def __init__(self, message):
        self.message = message

    def fail_information(self):
        print(self.message)


# 类:库函数执行错误,打印错误类型方法
class LibaryRuningError(Exception):
    def __init__(self, message):
        self.message = message

    def fail_information(self):
        print(self.message)

yes_no_exit.py :简单的判断 是、否、退出的配置文件,可以增加碰撞的字符。

# coding:utf-8

judgeYesNoExit={'y':['y','yes','是'],'n':['n','no','否'],'exit':['exit','退出']}

time_trigger.bat :简单的批处理,告诉操作系统该去什么路径下,执行什么文件

cd… & Tool.py

_(:з」∠)_别怀疑,就上面这点玩意儿,作用是退出当前路径,找到Tool.py 并运行它。

欧克!
在这里插入图片描述你以为这样就结束了了么?

在这里插入图片描述
自由意志是什么,百科里解释有为人的主观能动性,能不能动我说了不算,得借助工具才行呀,人的主观能惰性我倒是略懂一二,废话不多说,咱们直接开始 配置windows的定时任务。

在这里插入图片描述
win徽标+R 输入 compmgmt.msc

在这里插入图片描述
进入计算机管理,找到指定的菜单,创建任务

在这里插入图片描述知道我前面为什么叫它旺财系统了么

在这里插入图片描述
注意这里要点选 只在用户登录时运行 ,不然后面你测试任务运行的时候 只显示 正在运行任务0x14301

在这里插入图片描述
触发器自己设置,我就设置成每月提醒

在这里插入图片描述
操作这里一个是 bat 文件,一个是 bat 文件的路径就行

在这里插入图片描述后面的配置自己看看配置就行

在这里插入图片描述
好了,咱们手动执行一下任务,看看它到底能动不能动:

在这里插入图片描述
在这里插入图片描述在这里插入图片描述在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
欧克了!

在这里插入图片描述但是

文章结语

哲学里对自由意志没有确切的定义和解释,姑且就当做是多少亿年前,某个细胞发了牢骚,最后演变成为现在的人的神话故事吧。其实任何一点的逻辑都与其本身和周遭事物息息相关,如果计算能力超过光速,在光干扰该物质之前推算出任何一点都不能干扰该物质的域里发生的关于该物质的所有可能性事件,并能关联其余各点之间的联系,那么你就决定了这个物质在此域下的未来,当然也不是绝对的,如果该物质存在你已知算法的未知可能性的(域、对象、方法),或者在你定时开关打开研判结果发生之前,域的外界事物对域里的物质产生了新的影响,那么还是有可能导致最终结果不符或者有偏差的,但就现在人类的宇宙(视界下宇宙可能是宏观宇宙的一部分)而言,如此强大包含复杂可能性的模型也只能是未知的宇宙啦。人既依赖于工具的强大,又害怕失去自我自由的一部分成为工具下局限模型的一个实例, 如果已知(域、对象、方法)处理 未知(事件)得到最优解的可能性?为自由意志,也表示为你愿意去做这件事的你对自己能力的估量促使你去行动的…那么…

在这里插入图片描述

废话不多说,咱们还是进一步聊一聊咱们的旺财系统_(:з」∠)_,单论个体而言,相关因素包括了职业发展(管理:人生导师、技术:现代达芬奇或米开朗琪罗)、个人教育(知识的维度和专业性)、身心健康(身心年龄、饮食、休息、运动)等等,并且还有修仙任务和渡劫任务等着呢,所以这又是一个全人生周期的大工程项目…
在这里插入图片描述备注:上面系统运行的截图有修改代码的时间差,参考样式即可,代码改了,图就不改了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PythonExcel的交互是通过使用一些库来实现的。其中常用的库有xlwings、openpyxl、xlrd和xlwt等。xlwings提供了读取、写入和修改Excel的功能,可以方便地操作Excel文件。openpyxl也可以用于读取、写入和修改Excel文件。而xlrd和xlwt则是专门用于读取和写入Excel文件的库。 Python可以为Excel做很多事情。比如,可以使用Python读取Excel文件中的数据,进行数据处理和分析,然后将结果写回到Excel文件中。Python还可以自动化Excel操作,例如自动创建和保存Excel文件,自动填充数据,自动进行计算和数据筛选等等。此外,Python还可以与其他库结合使用,比如Pandas和Matplotlib,来进行更复杂的数据处理和可视化操作。总的来说,Python提供了丰富的功能和灵活性,可以帮助用户最大化地发挥Excel的能力。 因此,通过使用合适的库和工具,Python可以成为Excel用户的得力助手,帮助用户更高效地处理和分析Excel数据,并实现更多的功能和任务。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [全网最全Python操作Excel教程](https://blog.csdn.net/weixin_43820813/article/details/124467183)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [一日一技:Python + Excel——飞速处理数据分析与处理](https://blog.csdn.net/m0_59485658/article/details/125934615)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值