【Python编程】MemoAdmin (Mark)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39591494/article/details/84950369

MemoAdmin (Mark)


excel


#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import openpyxl
import datetime
import time
from core import loglog

log = loglog.yankerp()
year_list = [2013, 2014, 2015, 2016, 2017, 2018]


def excel(file_result, text_name, file_save):
    """
    程序功能-分析btc.xlsx 文件,并保存
    """
    wb = openpyxl.load_workbook(file_result)
    sh = wb.active
    index = 0
    for i in range(len(year_list)):
        count = 2
        sh1 = wb.create_sheet(str(year_list[index]))

        for rows in sh.rows:
            if rows[0].coordinate != "A1" and datetime.datetime.strptime(rows[0].value, '%Y-%m-%d %H:%M:%S %Z').year == year_list[index]:
                # print(rows[0].value, rows[1].value)
                sh1["A1"] = "日期"
                sh1["B1"] = "金额"
                sh1["A" + str(count)] = rows[0].value
                sh1["B" + str(count)] = rows[1].value

                # print("in sh:", sh1["A" + str(count)].value, sh1["B" + str(count)].value)
                print(f"正在分析{year_list[index]}年数据.....")
                count += 1
        index += 1
    wb.save(file_save + ".xlsx")


def main():
    "excel程序入口,接收文件路径-文件名称"
    Your_excel_text = input("请您输入需要分析excel文件的路径:").strip()
    file_name = input("请您输入excel文件名称:").strip()
    text_name = input("请您输入分析完成后的文件名称:").strip()

    file_result = os.path.join(Your_excel_text, file_name)
    file_save = os.path.join(Your_excel_text, text_name)
    start = time.time()
    excel(file_result, text_name, file_save)
    
    print(f"分析完成,用时{time.time() - start}秒,文件路径为:{file_save}")

loglog


#!/usr/bin/env python

import logging
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def yankerp(logger_name="memo.log", log_file=os.path.join(BASE_DIR, "log", "memo.log"), level=logging.DEBUG):
    # 创建logger对象
    logger = logging.getLogger(logger_name)
    logger.setLevel(level) # 添加等级

    # 创建控制台

    ch = logging.StreamHandler()
    ch.setLevel(level)

    # 创建文件
    fh =  logging.FileHandler(filename=log_file, encoding="utf-8")

    # create formatter
    formatter = logging.Formatter("%(asctime)s %(filename)s [line:%(lineno)d] %(name)s %(levelname)s %(message)s")

    ch.setFormatter(formatter)
    fh.setFormatter(formatter)

    logger.addHandler(ch)
    logger.addHandler(fh)

    return logger

memo


#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import time
import pickle
import sys
import configparser
import PyPDF2
from core import loglog


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
users_config_ini = os.path.join(BASE_DIR, "db", "users.ini")

log = loglog.yankerp()
__Author__ = "Memorandum"
print(f"Welcome to the {__Author__} System...".center(50, "-"))
memo_data = []


def memo(Your_title, Your_content, Your_Timespent):
    '备忘录主功能函数,保存事件,内容,用时时间等数据'
    data_memo = {}
    if Your_title.strip() == "" or Your_content.strip() == "":
        print("标题及内容不能为空!!!")
    else:
        data_memo["事件"] = Your_title
        data_memo["内容"] = Your_content
        data_memo["用时时间"] = Your_Timespent
        log.info("您已经生成一条备忘录信息...")
        text_file = os.path.join(BASE_DIR, "db", time.strftime("%Y-%m-%d_", time.localtime()) + "memo.txt")
        memo_data.append(data_memo) 
        for i in memo_data:
            for k, v in i.items():
                print(f"{k}:{v}")
            f = open(text_file, "a+")
            date = time.strftime("%Y-%m-%d %X", time.localtime())
            f.write(f"事件:{Your_title} | 内容:{Your_content} | 用时时间:{Your_Timespent} | 记录时间:{date}" +  "\n")
            f.close()
            log.info(f"您已经记录了{len(memo_data)}条备忘录信息,您是否还需要继续写入备忘录(yes/no)?")
        Count = True
        while(Count):
            You = input("请您选择:").strip()
            if You == "yes":
                Count = False
            elif You == "no":
                log.info("您已经退出了备忘录程序...")
                sys.exit()
            else:
                log.error("您输入的内容有误,请您重新输入!!!")
                Count = True


def main():
    '程序主入口,接收用户输入的事件,内容,时间,调用功能函数'
    Count = True
    while(Count):
        Your_title = input("请您输入您的事件:").strip()
        Your_content = input("请您输入您的内容:").strip()
        Your_Timespent = input("请您输入您的用时时间:").strip()

        memo(Your_title, Your_content, Your_Timespent)

user_login_memo


#!/usr/bin/env python
# -*- coding:utf-8 -*-

import pickle
import os
import sys
import configparser
import PyPDF2
from core import memo
from core import loglog
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO

__Author__ = "YanZanG"

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
log = loglog.yankerp()
users_data = os.path.join(BASE_DIR, "db", "memo_data.txt")
users_config_ini = os.path.join(BASE_DIR, "db", "users.ini")

data = {
    "DEFAULT" : {
        "basedir": BASE_DIR,
        "name" : "memo",
        "users_data" : users_data,
        "users_config_ini" : users_config_ini
    },
}

print(f"Welcome to the {__Author__} memorandum".center(50, "-"))
print("Note: Registration is required for first use".center(50, "-"))


class Users():
    """
    此类包含用户注册、用户数据保存、配置文件写入
    """
    def __init__(self, Your_user_name, Your_user_password, data):
        self.Your_user_name = Your_user_name
        self.Your_user_password = Your_user_password
        self.db_file_path = os.path.join(BASE_DIR, "db", "users.pkl")
        self.User_data_list = []
        self.User_data = {}
        self.data = data

    def user_zc(self):
        """
        用户注册各个功能
        """
        if self.Your_user_name == "" or self.Your_user_password == "":
            print("用户名或密码不能为空,请您重新输入!!!")
            Count = True
        else:
            self.User_data["用户名"] = self.Your_user_name
            self.User_data["密码"] = self.Your_user_password
            self.User_data_list.append(self.User_data)
            self.user_save()
            self.write_config()

    def user_save(self):
        """
        保存用户数据功能
        """
        with open(self.db_file_path, "wb") as f:
            pickle.dump(self.User_data_list, f)
        log.info("用户名密码保存成功,以下是您的用户名及密码".center(50, "-"))
        for k, v in self.User_data.items(): 
            print(f"{k} : {v}")
    
    def write_config(self):
        """
        将用户数据,用户名密码写入到配置文件.
        """
        config = configparser.ConfigParser()
        for k, v in self.data.items():
            config[k] = v
            config.add_section(self.Your_user_name)
            config.set(self.Your_user_name, "user_name", self.Your_user_name)
            config[self.Your_user_name]["password"] = self.Your_user_password
            with open(users_config_ini, "w") as f:
                config.write(f)
        
        log.info("主配置文件加载成功!!!")


def user_registered(data):
    """
    用户注册函数入口
    """
    Count = True
    while(Count):
        Your_user_name = input("请您设置您的用户名:").strip()
        Your_user_password = input("请您设置您的密码:").strip()

        if Your_user_name == "" or Your_user_password == "":
            print("用户名或密码不能为空,请您重新输入!!!")
            Count = True
        else:
            A = Users(Your_user_name, Your_user_password, data)
            A.user_zc()
            Count = False


class User_login():
    """
    用户登陆类,此类提供用户登陆并调用备忘录功能函数
    """
    def __init__(self, user_login_name, user_login_password, data):
        self.user_login_name = user_login_name
        self.user_login_password = user_login_password
        self.db_file_path = os.path.join(BASE_DIR, "db", "users.pkl")
        self.data = data

    def name_load(self):
        """
        判断用户输入的用户名密码是否正确,若不正确调用注册类,若正确调用备忘录函数
        """
        if os.path.exists(self.db_file_path):
            with open(self.db_file_path, "rb") as f:
                data = pickle.load(f)
                for key in data:
                    for k, v in key.items():
                        if v == self.user_login_name or v == self.user_login_password:
                            log.info("用户名密码正确,备忘录登录成功!!!")
                            memo.main()
                        else:
                            print("这个用户不存在,您是否需要注册?(yes/no)?")
                            you = input("请您输入您的选择:").strip()
                            if you == "yes":
                                user_registered(self.data)
                                Count =  False
                            elif you == "no":
                                sys.exit("您选择了退出.")
                            else:
                                print("系统检测您输入的内容失败,请您重新输入选择!!!")
                                Count = True
        else:
            Count = True
            while(Count):
                print("第一次登陆需要注册用户信息.您是否需要注册(yes/no)?")
                you = input("请您输入您的选择:").strip()
                if you == "yes":
                    user_registered(self.data)
                    Count =  False
                elif you == "no":
                    sys.exit("您选择了退出.")
                else:
                    print("系统检测您输入的内容失败,请您重新输入选择!!!")
                    Count = True


def user_name_login():
    """
    用户登陆主函数入口
    """
    Count = True
    while(Count):
        Your_user_name = input("请您输入您的用户名:").strip()
        Your_user_password = input("请您输入您的密码:").strip()

        A = User_login(Your_user_name, Your_user_password, data)
        A.name_load()


def menu():
    """
    使用此程序的主入口函数,提供用户菜单选择,调用不同的函数.
    """
    Count = True
    while(Count):
        Menu = {
            "1" : "注册账户",
            "2" : "登陆备忘录",
            "q" : "退出程序"
        }
        
        for k, v in Menu.items():
            print(f"{k}、{v}")
        
        Your_choice = input("请您输入:").strip().upper()
        if Your_choice == "":
            log.error("对不起,您输入的选择不能为空,请您重新输入".center(50, "-"))
            Count = True
        elif Your_choice == "1":
            user_registered(data)
        elif Your_choice == "2":
            user_name_login()
        elif Your_choice == "Q":
            sys.exit()
        else:
            log.error("对不起,系统未能识别您输入的内容,请您重新输入...")
            Count = False

word


#!/usr/bin/env python
# -*- coding:utf-8 -*-

from docx import Document
import os
import sys


class Document_word:
    """
    此类提供word文档的标题,副标题、正文、保存功能
    """
    def __init__(self, doc_text_path, doc_name, doc_title, doc_subtitle, doc_text, index):
        self.Doc = Document()
        self.doc_text_path = doc_text_path
        self.doc_name = doc_name
        self.doc_title = doc_title
        self.doc_subtitle = doc_subtitle
        self.doc_text = doc_text
        self.index = index

    def add_title(self):
        """
        Word文档标题功能
        """
        self.index += 1
        self.Doc.add_heading(self.doc_title, level=self.index)

    def add_subtitle(self):
        """
        word文档副标题功能
        """
        self.Doc.add_paragraph(self.doc_subtitle, "Subtitle")

    def add_text(self):
        """
        添加正文功能
        """
        self.Doc.add_paragraph(self.doc_text)

    def save_doc(self):
        """
        保存word文档功能
        """
        doc_path = os.path.join(self.doc_text_path, self.doc_name)
        self.Doc.save(doc_path)
        print(f"恭喜您写入成功,存放路径为{self.doc_text_path}文档名称为:{self.doc_name}")
        sys.exit()


def content(file_path, file_name):
    """
    此函数接受用户输入的标题,内容,并调用Word类
    """
    Count = True
    index = 0 
    while(Count):
        index += 1
        content_title = input("请您输入内容标题:").strip()
        content_subtitle = input("请您输入内容副级标题:").strip()
        content_text = input("请您输入正文文章内容:").strip()
        
        DOC = Document_word(file_path, file_name, content_title, content_subtitle, content_text, index)
        DOC.add_title()
        DOC.add_subtitle()
        DOC.add_text()

        print("恭喜您,写入成功,是否修改写入内容(yes/no)?") 
        your = input(">>>")
        if your == "yes":
            Count = True
        else:
            DOC.save_doc()
            Count = False


def file_path():
    """
    此函数提供接受用户输入路径,文档名称,判断路径是否正确.
    """
    Count = True
    while(Count):
        file_path = input("请您输入需要保存的路径:").strip()
        file_name = input("请您输入需要保存的文档名称:").strip() + ".docx"

        if os.path.isdir(file_path):
            content(file_path, file_name)
        else:
            print("检测目录失败,请重新输入目录.")
            Count = True

mian()


#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from core import excel
from core import memo
from core import user_login_memo
from core import word


def menu():
    '程序主入口,提供用户选择菜单'
    Count = True
    while(Count):
        menu = {
            "1" : "word文档编辑",
            "2" : "excel数据分析",
            "3" : "备忘录程序",
            "q" : "退出此程序"
        }
        
        for k, v in menu.items():
            print(f"{k}、{v}")

        You = input("请您选择:").strip().upper()

        if You == "1":
            word.file_path()
        elif You == "2":
            excel.main()
        elif You == "3":
            user_login_memo.menu()
        elif You == "Q":
            sys.exit()

if __name__ == "__main__":
    menu()

猜你喜欢

转载自blog.csdn.net/qq_39591494/article/details/84950369
今日推荐