当前位置: 首页 > news >正文

一个python整理笔记脚本

测试代码

import os
import re
import customtkinter as ctk
from datetime import datetime
from tkinter import filedialog, messagebox

# 设置界面主题
ctk.set_appearance_mode("System") # 自动切换深/浅色
ctk.set_default_color_theme("blue")

class WorkReporterGUI(ctk.CTk):
def __init__(self):
super().__init__()

self.title("Markdown 工作汇总生成器")
self.geometry("600x450")

# 变量
self.target_path = ctk.StringVar(value=os.getcwd())

# 创建布局
self.setup_u()

def setup_u(self):
# 标题
self.label_title = ctk.CTkLabel(self, text="个人工作周报汇总工具", font=ctk.CTkFont(size=20, weight="bold"))
self.label_title.pack(pady=20)

# 路径选择区
self.frame_path = ctk.CTkFrame(self)
self.frame_path.pack(pady=10, padx=20, fill="x")

self.entry_path = ctk.CTkEntry(self.frame_path, textvariable=self.target_path, width=400)
self.entry_path.pack(side="left", padx=10, pady=10)

self.btn_browse = ctk.CTkButton(self.frame_path, text="选择目录", width=80, command=self.browse_folder)
self.btn_browse.pack(side="right", padx=10)

# 选项
self.label_hint = ctk.CTkLabel(self, text="提示:将扫描目录下形如 251230.md 的文件", font=ctk.CTkFont(size=12))
self.label_hint.pack(pady=5)

# 运行按钮
self.btn_run = ctk.CTkButton(self, text="开始生成汇总表", command=self.process, height=50, font=ctk.CTkFont(size=16, weight="bold"))
self.btn_run.pack(pady=30)

# 日志输出区
self.log_text = ctk.CTkTextbox(self, height=150)
self.log_text.pack(pady=10, padx=20, fill="both")

def browse_folder(self):
path = filedialog.askdirectory()
if path:
self.target_path.set(path)

def log(self, message):
self.log_text.insert("end", f"[{datetime.now().strftime('%H:%M:%S')}] {message}\n")
self.log_text.see("end")

def get_weekday_cn(self, dt):
return ["周一", "周二", "周三", "周四", "周五", "周六", "周日"][dt.weekday()]

def process(self):
root_dir = self.target_path.get()
output_file = os.path.join(root_dir, "工作汇总表.md")
all_days_data = []
title_pattern = re.compile(r'^###\s+(.+)')

try:
self.log("正在扫描文件...")
for root, dirs, files in os.walk(root_dir):
for file in files:
if file == "工作汇总表.md" or not file.endswith(".md"): continue
if len(file) == 9: # 251230.md
date_part = file.split('.')[0]
try:
dt = datetime.strptime(date_part, "%y%m%d")
except: continue

file_path = os.path.join(root, file)
rel_path = os.path.relpath(file_path, start=root_dir)

events = []
with open(file_path, 'r', encoding='utf-8') as f:
in_code_block = False
for line in f:
if line.strip().startswith('```'):
in_code_block = not in_code_block
continue
if not in_code_block:
match = title_pattern.match(line)
if match: events.append(match.group(1).strip())

if events:
week_num = dt.strftime("%W")
all_days_data.append({
"dt": dt, "year": dt.year, "week_key": f"{dt.year}年-第{week_num}周",
"date_str": dt.strftime("%Y-%m-%d"), "weekday_cn": self.get_weekday_cn(dt),
"rel_path": rel_path, "events": events
})

if not all_days_data:
self.log("未找到有效记录!")
return

# 构建表格
weeks_dict = {}
for day in all_days_data:
weeks_dict.setdefault(day["week_key"], []).append(day)

sorted_week_keys = sorted(weeks_dict.keys(), reverse=True)
table_lines = [f"# 📝 工作汇总 ({datetime.now().strftime('%Y-%m-%d')})\n\n", "| 日期 | 周几 | 序号 | 标题内容 |", "| :--- | :--- | :--- | :--- |"]

last_year = None
for week_key in sorted_week_keys:
days = sorted(weeks_dict[week_key], key=lambda x: x["dt"])
curr_year = days[0]["year"]

if last_year and last_year != curr_year:
table_lines.append(f"| 🎊 | **{last_year} 年结束** | --- | **进入 {curr_year} 年度** |")

for d in days:
for idx, title in enumerate(d["events"], 1):
d_col = f"[{d['date_str']}]({d['rel_path']})" if idx == 1 else ""
w_col = d["weekday_cn"] if idx == 1 else ""
table_lines.append(f"| {d_col} | {w_col} | {idx} | {title} |")

table_lines.append(f"| --- | --- | --- | **{week_key} 回顾** |")
last_year = curr_year

with open(output_file, "w", encoding="utf-8") as f:
f.write("\n".join(table_lines))

self.log(f"成功!汇总表已生成。")
if messagebox.askyesno("完成", "汇总表已生成!是否立即打开查看?"):
os.startfile(output_file) if os.name == 'nt' else os.system(f'open "{output_file}"')

except Exception as e:
self.log(f"发生错误: {str(e)}")
messagebox.showerror("错误", str(e))

if __name__ == "__main__":
app = WorkReporterGUI()
app.mainloop()

http://www.gsyq.cn/news/181974.html

相关文章:

  • Miniconda-Python3.9如何支持PyTorch与Homomorphic Encryption集成
  • 推荐几家TikTok营销服务商,五家效果不错的TikTok代运营公司、TikTok海外推广公司详细介绍 - 品牌2025
  • 2025—2026年液压机厂家推荐:闭式液压机/框架液压机/冲床液压机/315吨框架式液压机/315吨液压机/500吨液压机优质厂商深度对比! - 海棠依旧大
  • 2026软件测试工程师经典面试题
  • 2025Q4升降机厂家推荐榜:苏州卓高登顶,专精品牌成采购优选 - 品牌智鉴榜
  • Miniconda-Python3.9镜像支持Jupyter Lab的配置方法
  • PyTorch健康检查接口开发:Miniconda-Python3.9环境测试
  • PyTorch在线推理服务构建:Miniconda-Python3.9环境支撑
  • Miniconda-Python3.9安装PyYAML、NumPy等常用库指南
  • 抱歉,系统超时,请稍后重试。
  • PyTorch容错机制设计:基于Miniconda-Python3.9环境验证
  • 学长亲荐10个AI论文工具,MBA毕业论文轻松搞定!
  • 收藏!深入浅出Transformer核心架构:Encoder与Decoder实战指南
  • 护网新手集合!平民化挖掘技巧 + 实战例子,你们踩过哪些坑?评论区聊聊!
  • 赋能研发升级:IPD管理咨询的标杆案例与核心方案
  • java计算机毕业设计校园招聘管理系统 高校毕业生智慧就业撮合平台 校企协同实习与招聘一体化系统
  • 【UE】优化技巧:将造成卡顿的主线程任务,分散到多个帧进行分帧处理
  • Miniconda-Python3.9配合VS Code远程开发指南
  • 【必收藏】2025中国AI大模型狂飙史:从技术突破到产业赋能的全面解析
  • upload markdown - ling
  • Java开发者转型AI大模型完全指南:从零到专家的进阶路径_Java程序员转型大模型应用开发
  • Qt - QByteArray和char[]的区别
  • 淄博抖音代运营公司哪家更靠谱?2025年终7家服务商权威评测与最终推荐! - 品牌推荐
  • 感知机(感知机的局限性)
  • 分布式锁与重试机制标准化方案
  • 在有网Windows机器A上使用conda-pack打包虚拟环境,然后迁移到无网Windows机器B
  • 使用Miniconda-Python3.9搭建BERT文本分类PyTorch实验环境
  • NVIDIA Container Toolkit 安装
  • PyTorch缓存机制优化:基于Miniconda-Python3.9环境测试
  • Miniconda-Python3.9环境下使用TorchScript保存和加载模型