1. 程式人生 > >使用Python編寫Word文件v1

使用Python編寫Word文件v1

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

__Author__ = "YanZanG"
__product__ = "Spiritual conversion"


import PyPDF2
import openpyxl
import os
import sys
from docx import Document
from color_me import ColorMe

class Office(object):
    def __init__(self, file_path, file_name):
        self.file_path =
file_path self.file_name = file_name self.Doc = Document() self.index = 0 def user_input(self): os.chdir(self.file_path) Count = True while (Count): Your_add_heading = input("請您輸入標題:") Your_add_paragraph = input("請您輸入內容:") if
Your_add_heading.strip() == "" or Your_add_paragraph.strip() == "": print("標題或者內容不能為空,請您重新輸入!!!") Count = True else: self.write(Your_add_heading, Your_add_paragraph) Count = False def write(self, Your_add_heading, Your_add_paragraph)
: self.index += 1 self.Doc.add_heading(Your_add_heading, level=self.index) self.Doc.add_paragraph(Your_add_paragraph) self.carry() def carry(self): Count = True while(Count): print("你是否還需要繼續新增內容?(yes/no)") User_result = input("請您選擇:").upper() if User_result.strip() == "": print("對不起,選擇不能為空呀") elif User_result.strip() == "YES": self.user_input() elif User_result.strip() == "NO": self.Doc.save(self.file_name + ".docx") print("儲存並退出成功,請您立即檢視,歡迎再次使用,Bye~") sys.exit() def main(): welcome = ColorMe(f"Welcome to the {__product__} applet".center(60,"_")).green() print(welcome) Info_error = ColorMe("輸入路徑例如:F:\python-office").green() Count = True while(Count): Your_path = input("請您輸入您需要儲存的路徑:").strip() Your_file_name = input("為你的情書起一個名字吧:").strip() if os.path.exists(Your_path): Success = ColorMe(f"系統檢測{Your_path}路徑成功!!!").green() print(Success) office_word = Office(Your_path, Your_file_name) office_word.user_input() Count = False else: file_error = ColorMe(f"系統檢測'{Your_path}'路徑失敗,請您輸入正確的儲存路徑").red() print(file_error) print(Info_error) if __name__ == '__main__': main()

Color_me:

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

__author__ = 'De8ug'

class ColorMe:
    """
    give me color see see...
    實際用起來很簡單:
        ColorMe('somestr').blue()
    """
    def __init__(self, some_str):
        self.color_str = some_str

    def blue(self):
        str_list = ["\033[34;1m", self.color_str, "\033[0m"]
        return ''.join(str_list) # "\033[34;1m" + self.color_str + "\033[0m"

    def green(self):
        str_list = ["\033[32;1m", self.color_str, "\033[0m"]
        return ''.join(str_list) # "\033[34;1m" + self.color_str + "\033[0m"

    def yellow(self):
        str_list = ["\033[33;1m", self.color_str, "\033[0m"]
        return ''.join(str_list) # "\033[34;1m" + self.color_str + "\033[0m"

    def red(self):
        str_list = ["\033[31;1m", self.color_str, "\033[0m"]
        return ''.join(str_list) # "\033[34;1m" + self.color_str + "\033[0m"


def main():
    ColorMe('somestr').blue()

if __name__ == '__main__':
    main()

執行結果 在這裡插入圖片描述 在這裡插入圖片描述