Skip to content

Commit

Permalink
優化程式碼
Browse files Browse the repository at this point in the history
  • Loading branch information
AlanJui committed Jan 11, 2025
1 parent 43d6a9e commit a8b5f22
Show file tree
Hide file tree
Showing 3 changed files with 135 additions and 97 deletions.
58 changes: 32 additions & 26 deletions a700_重置漢字標音工作表.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# =========================================================================
# 載入程式所需套件/模組/函式庫
# =========================================================================
import logging
import os
import sys
Expand Down Expand Up @@ -28,6 +31,10 @@
format='%(asctime)s - %(levelname)s - %(message)s'
)

def logging_process_step(msg):
print(msg)
logging.info(msg)

# =========================================================================
# 定義 Exit Code
# =========================================================================
Expand All @@ -38,14 +45,7 @@
EXIT_CODE_UNKNOWN_ERROR = 99 # 未知錯誤

# =========================================================================
# 定義 Exit Code
# =========================================================================
def logging_process_step(msg):
print(msg)
logging.info(msg)

# =========================================================================
# 本程式主要處理作業程序
# 作業程序
# =========================================================================
def process(wb):
#--------------------------------------------------------------------------
Expand Down Expand Up @@ -77,13 +77,22 @@ def process(wb):
logging_process_step(f"【漢字注音】工作表的清空、重置失敗!")
return EXIT_CODE_PROCESS_FAILURE

#--------------------------------------------------------------------------
# 作業結尾處理
#--------------------------------------------------------------------------
wb.save()
return EXIT_CODE_SUCCESS


# =========================================================================
# 程式主要作業流程
# =========================================================================
# =============================================================================
# 程式主流程
# =============================================================================
def main():
# =========================================================================
# 開始作業
# =========================================================================
logging.info("作業開始")

# =========================================================================
# (1) 取得專案根目錄。
# =========================================================================
Expand All @@ -92,20 +101,19 @@ def main():
logging_process_step(f"專案根目錄為: {project_root}")

# =========================================================================
# (2) 若無指定輸入檔案,則獲取當前作用中的 Excel 檔案並另存新檔
# (2) 設定【作用中活頁簿】:偵測及獲取 Excel 已開啟之活頁簿檔案
# =========================================================================
wb = None
# 使用已打開且處於作用中的 Excel 工作簿
# 取得【作用中活頁簿】
try:
# 嘗試獲取當前作用中的 Excel 工作簿
wb = xw.apps.active.books.active
wb = xw.apps.active.books.active # 取得 Excel 作用中的活頁簿檔案
except Exception as e:
logging_process_step(f"發生錯誤: {e}")
print(f"發生錯誤: {e}")
logging.error(f"無法找到作用中的 Excel 工作簿: {e}", exc_info=True)
return EXIT_CODE_NO_FILE

# 若無法取得【作用中活頁簿】,則因無法繼續作業,故返回【作業異常終止代碼】結束。
if not wb:
logging_process_step("無法作業,因未無任何 Excel 檔案己開啟。")
return EXIT_CODE_NO_FILE

# =========================================================================
Expand All @@ -114,32 +122,30 @@ def main():
try:
result_code = process(wb)
if result_code != EXIT_CODE_SUCCESS:
logging_process_step("處理作業失敗,過程中出錯!")
logging_process_step("作業異常終止!")
return result_code

except Exception as e:
print(f"執行過程中發生未知錯誤: {e}")
logging.error(f"執行過程中發生未知錯誤: {e}", exc_info=True)
print(f"作業過程發生未知的異常錯誤: {e}")
logging.error(f"作業過程發生未知的異常錯誤: {e}", exc_info=True)
return EXIT_CODE_UNKNOWN_ERROR

finally:
if wb:
wb.save()
# 是否關閉 Excel 視窗可根據需求決定
# xw.apps.active.quit() # 確保 Excel 被釋放資源,避免開啟殘留
logging.info("釋放 Excel 資源,處理完成。")
logging.info("a700_重罝漢字標音工作表.py 程式已執行完畢!")

# =========================================================================
# 結束作業
# =========================================================================
logging.info("作業成功完成!")
logging.info("作業完成!")
return EXIT_CODE_SUCCESS


if __name__ == "__main__":
exit_code = main()
if exit_code == EXIT_CODE_SUCCESS:
print("作業正常結束!")
print("程式正常完成!")
else:
print(f"作業異常終止,錯誤代碼為: {exit_code}")
print(f"程式異常終止,錯誤代碼為: {exit_code}")
sys.exit(exit_code)
159 changes: 92 additions & 67 deletions a701_作業中活頁檔填入漢字.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# =========================================================================
# 載入程式所需套件/模組/函式庫
# =========================================================================
import logging
import os
import sys
Expand Down Expand Up @@ -32,6 +35,10 @@
format='%(asctime)s - %(levelname)s - %(message)s'
)

def logging_process_step(msg):
print(msg)
logging.info(msg)

# =========================================================================
# 定義 Exit Code
# =========================================================================
Expand All @@ -42,6 +49,74 @@
EXIT_CODE_UNKNOWN_ERROR = 99 # 未知錯誤


# =========================================================================
# 作業程序
# =========================================================================
def process(wb):
# ---------------------------------------------------------------------
# 取得【待注音漢字】總字數
# ---------------------------------------------------------------------
cell_value = wb.sheets['漢字注音'].range('V3').value

if cell_value is None:
print("【待注音漢字】儲存格未填入文字,作業無法繼續。")
logging.warning("【待注音漢字】儲存格為空")
return EXIT_CODE_INVALID_INPUT

value_length = len(cell_value.strip())
print(f"【待注音漢字】總字數為: {value_length}")
logging.info(f"【待注音漢字】總字數為: {value_length}")

# ---------------------------------------------------------------------
# 執行儲存格重設作業
# ---------------------------------------------------------------------
print("清除儲存格內容...")
clear_han_ji_kap_piau_im(wb)
logging.info("儲存格內容清除完畢")

print("重設儲存格之格式...")
reset_han_ji_cells(wb)
logging.info("儲存格格式重設完畢")

print("待注音漢字填入【漢字注音】工作表...")
fill_hanji_in_cells(wb)
logging.info("待注音漢字已填入【漢字注音】工作表")

# ---------------------------------------------------------------------
# 為漢字查找標音
# ---------------------------------------------------------------------
type = get_sound_type(wb)
han_ji_khoo = get_han_ji_khoo(wb)

if han_ji_khoo in ["河洛話", "廣韻"]:
db_name = DB_HO_LOK_UE if han_ji_khoo == "河洛話" else DB_KONG_UN
module_name = 'mod_河洛話' if han_ji_khoo == "河洛話" else 'mod_廣韻'
ue_im_lui_piat = type if han_ji_khoo == "白話音" else "文讀音"

# 查找漢字標音
logging.info(f"開始【漢字標音作業】 - {han_ji_khoo}: {type}")
ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3',
ue_im_lui_piat=ue_im_lui_piat,
han_ji_khoo=han_ji_khoo, db_name=db_name,
module_name=module_name,
function_name='han_ji_ca_piau_im')
logging.info(f"完成【漢字標音作業】 - {han_ji_khoo}: {type}")
else:
print("無法執行【漢字標音作業】,請確認設定是否正確!")
logging.warning("無法執行【漢字標音作業】,需檢查【env】工作表之設定。")
return EXIT_CODE_PROCESS_FAILURE

# ---------------------------------------------------------------------
# 作業結尾處理
# ---------------------------------------------------------------------
file_path = save_as_new_file(wb=wb)
logging.info("己存檔至路徑:{file_path}")
return EXIT_CODE_SUCCESS


# =============================================================================
# 程式主流程
# =============================================================================
def main():
logging.info("作業開始")

Expand All @@ -54,97 +129,47 @@ def main():
logging.info(f"專案根目錄為: {project_root}")

# =========================================================================
# (2) 嘗試獲取當前作用中的 Excel 工作簿
# (2) 設定【作用中活頁簿】:偵測及獲取 Excel 已開啟之活頁簿檔案。
# =========================================================================
wb = None
# 取得【作用中活頁簿】
try:
wb = xw.apps.active.books.active
wb = xw.apps.active.books.active # 取得 Excel 作用中的活頁簿檔案
except Exception as e:
print(f"發生錯誤: {e}")
logging.error(f"無法找到作用中的 Excel 工作簿: {e}", exc_info=True)
print("無法找到作用中的 Excel 工作簿")
return EXIT_CODE_NO_FILE

# 若無法取得【作用中活頁簿】,則因無法繼續作業,故返回【作業異常終止代碼】結束。
if not wb:
print("無法作業,原因可能為:(1) 未指定輸入檔案;(2) 未找到作用中的 Excel 工作簿!")
logging.error("無法作業,未指定輸入檔案或 Excel 無效。")
return EXIT_CODE_NO_FILE

# =========================================================================
# (3) 執行【處理作業】
# =========================================================================
try:
# =========================================================================
# (3) 讀取儲存格資料
# =========================================================================
cell_value = wb.sheets['漢字注音'].range('V3').value

if cell_value is None:
print("【待注音漢字】儲存格未填入文字,作業無法繼續。")
logging.warning("【待注音漢字】儲存格為空")
return EXIT_CODE_INVALID_INPUT

value_length = len(cell_value.strip())
print(f"【待注音漢字】總字數為: {value_length}")
logging.info(f"【待注音漢字】總字數為: {value_length}")

# =========================================================================
# (4) 執行 Excel 作業
# =========================================================================
print("正在清除儲存格...")
clear_han_ji_kap_piau_im(wb)
logging.info("儲存格清除完畢")

print("重設格式...")
reset_han_ji_cells(wb)
logging.info("儲存格格式重設完畢")

print("填入待注音漢字...")
fill_hanji_in_cells(wb)
logging.info("填入待注音漢字完成")

# =========================================================================
# (5) 自動查找讀音
# =========================================================================
type = get_sound_type(wb)
han_ji_khoo = get_han_ji_khoo(wb)

if han_ji_khoo in ["河洛話", "廣韻"]:
db_name = DB_HO_LOK_UE if han_ji_khoo == "河洛話" else DB_KONG_UN
module_name = 'mod_河洛話' if han_ji_khoo == "河洛話" else 'mod_廣韻'
hue_im = type if han_ji_khoo == "河洛話" else "文讀音"

logging.info(f"開始標音作業 - {han_ji_khoo}: {type}")
ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', hue_im=hue_im,
han_ji_khoo=han_ji_khoo, db_name=db_name,
module_name=module_name, function_name='han_ji_ca_piau_im')
logging.info(f"標音作業完成 - {han_ji_khoo}: {type}")
else:
print("無法執行漢字標音作業,請確認設定是否正確!")
logging.warning("無法執行標音作業,檢查【env】設定。")
return EXIT_CODE_PROCESS_FAILURE

# =========================================================================
# (6) 儲存檔案
# =========================================================================
print("儲存檔案...")
save_as_new_file(wb=wb)
logging.info("檔案已成功儲存")
result_code = process(wb)
if result_code != EXIT_CODE_SUCCESS:
logging_process_step("作業異常終止!")
return result_code

except Exception as e:
print(f"執行過程中發生未知錯誤: {e}")
logging.error(f"執行過程中發生未知錯誤: {e}", exc_info=True)
print(f"作業過程發生未知的異常錯誤: {e}")
logging.error(f"作業過程發生未知的異常錯誤: {e}", exc_info=True)
return EXIT_CODE_UNKNOWN_ERROR

finally:
if wb:
# 是否關閉 Excel 視窗可根據需求決定
# xw.apps.active.quit() # 確保 Excel 被釋放資源,避免開啟殘留
logging.error(f"作業正常完成!")
logging.info("a701_作業中活頁簿填入漢字.py 程式已執行完畢!")

return EXIT_CODE_SUCCESS


if __name__ == "__main__":
exit_code = main()
if exit_code == EXIT_CODE_SUCCESS:
print("作業成功完成!")
print("程式正常完成!")
else:
print(f"程式結束,代碼: {exit_code}")
print(f"程式異常終止,錯誤代碼為: {exit_code}")
sys.exit(exit_code)
15 changes: 11 additions & 4 deletions p702_Ca_Han_Ji_Thak_Im.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def za_ji_kiat_ko_cut_piau_im(result, han_ji_khoo, piau_im, piau_im_huat):
return tai_gi_im_piau, han_ji_piau_im


def ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', hue_im="白話音", han_ji_khoo="河洛話", db_name='Ho_Lok_Ue.db', module_name='mod_河洛話', function_name='han_ji_ca_piau_im'):
def ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', ue_im_lui_piat="白話音", han_ji_khoo="河洛話", db_name='Ho_Lok_Ue.db', module_name='mod_河洛話', function_name='han_ji_ca_piau_im'):
"""查漢字讀音:依【漢字】查找【台語音標】,並依指定之【標音方法】輸出【漢字標音】"""
# 動態載入查找函數
han_ji_ca_piau_im = load_module_function(module_name, function_name)
Expand Down Expand Up @@ -104,7 +104,9 @@ def ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', hue_im="白話
EOF = True
break
elif cell_value == '\n':
break
msg = "【換行】"
elif cell_value == None:
msg = "【空白】"
else:
# 若不為【標點符號】,則以【漢字】處理
if is_punctuation(cell_value):
Expand Down Expand Up @@ -177,7 +179,7 @@ def ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', hue_im="白話
print(f"漢字:【{han_ji}】之注音【{tai_gi_im_piau}】取自【人工注音字典】。")
# 若【破音字庫】無此漢字,則在資料庫中查找
else:
result = han_ji_ca_piau_im(cursor=cursor, han_ji=han_ji, hue_im=hue_im)
result = han_ji_ca_piau_im(cursor=cursor, han_ji=han_ji, hue_im=ue_im_lui_piat)
if not result:
msg = f"【{han_ji}】查無此字!"
else:
Expand All @@ -195,7 +197,12 @@ def ca_han_ji_thak_im(wb, sheet_name='漢字注音', cell='V3', hue_im="白話
sheet.range((row + 1, col)).value = han_ji_piau_im
msg = f"{han_ji}: [{tai_gi_im_piau}] /【{han_ji_piau_im}】"

print(f"({row}, {col_name}) = {msg}")
# 顯示處理進度
print(f"({row}, {col_name}) = {msg}")

# 若讀到【換行】,跳出逐欄取字迴圈
if msg == "【換行】":
break

# 每處理 15 個字元後,換到下一行
print("\n")
Expand Down

0 comments on commit a8b5f22

Please sign in to comment.