AI办公自动化实战:用Python+LLM把重复工作交给机器
AI办公自动化实战:用Python+LLM把重复工作交给机器
一、为什么要做办公自动化?
2026年,大部分知识工作者每天仍然花费40%以上的时间在处理重复性事务:整理报表、回复邮件、格式化文档、数据录入……这些工作不需要创意,不需要深度思考,但消耗了大量精力。
AI自动化的核心思路就是:把规则的重复工作交给机器,把创造性的工作留给自己。
本文分享4个可以直接落地的自动化实战案例,全部基于Python + LLM(大语言模型)实现。
二、必备工具链
在开始之前,你需要安装以下工具:
# Python环境(推荐3.11+)
pip install openai pandas openpyxl python-docx
# 可选:自动化的调度工具
# Windows: 任务计划程序(系统自带)
# Mac/Linux: cron
# 全平台: n8n (https://n8n.io)
另外需要一个LLM API Key,推荐使用DeepSeek(性价比高)或OpenAI的API。
案例1:智能日报自动生成
痛点:每天下班前花20分钟写日报,翻聊天记录、回想做了什么。
方案:读取当天的Git提交记录和聊天记录,自动生成日报。
import openai
from datetime import datetime, timedelta
import subprocess
def get_git_commits():
"""获取今天的所有git提交"""
today = datetime.now().strftime("%Y-%m-%d")
cmd = f'git log --since="{today} 00:00" --until="{today} 23:59" --format="%s"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
return result.stdout.strip().split("\n")
def generate_daily_report(commits):
"""用LLM生成日报"""
prompt = f"""请根据以下今日工作记录,生成一份规范的日报。
要求:
1. 按工作模块分类(开发、测试、文档等)
2. 每个模块列出具体完成事项
3. 附上明日计划(2-3项)
4. 语气简洁专业
今日记录:
{chr(10).join(commits)}
日报:"""
response = openai.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# 使用示例
commits = get_git_commits()
if commits and commits[0]:
report = generate_daily_report(commits)
print(report)
效果:原本20分钟的日报,现在一键生成,只花5秒钟核对即可。
案例2:Excel智能报表清洗
痛点:每周从系统导出的Excel数据五花八门,需要人工清洗、格式化、汇总。
方案:用Python自动化处理,LLM辅助复杂规则判断。
import pandas as pd
import openpyxl
from openpyxl.styles import Font, PatternFill
def clean_report(input_file, output_file):
"""智能清洗报表"""
df = pd.read_excel(input_file)
# 1. 自动检测并删除空行/空列
df = df.dropna(how='all')
df = df.dropna(axis=1, how='all')
# 2. 标准化日期格式
date_cols = df.select_dtypes(include=['datetime64']).columns
for col in date_cols:
df[col] = df[col].dt.strftime('%Y-%m-%d')
# 3. 金额列格式化
money_cols = [col for col in df.columns if '金额' in col or '价格' in col]
for col in money_cols:
df[col] = df[col].apply(lambda x: f"¥{x:,.2f}" if pd.notna(x) else x)
# 4. 高亮异常值(超过3倍标准差)
writer = pd.ExcelWriter(output_file, engine='openpyxl')
df.to_excel(writer, index=False, sheet_name='清洗后数据')
workbook = writer.book
worksheet = writer.sheets['清洗后数据']
red_fill = PatternFill(start_color='FFE0E0', end_color='FFE0E0', fill_type='solid')
for col_idx, col in enumerate(df.columns, 1):
if df[col].dtype in ['int64', 'float64']:
mean = df[col].mean()
std = df[col].std()
for row_idx in range(2, len(df) + 2):
value = worksheet.cell(row=row_idx, column=col_idx).value
if isinstance(value, (int, float)) and abs(value - mean) > 3 * std:
worksheet.cell(row=row_idx, column=col_idx).fill = red_fill
writer.close()
print(f"清洗完成,已保存至: {output_file}")
clean_report("原始报表.xlsx", "清洗后报表.xlsx")
效果:每周1小时的报表清洗工作,变为1分钟的脚本运行。
案例3:批量邮件自动回复分类
痛点:每天几十封客服邮件,需要人工分类再转发不同部门。
方案:LLM自动分类 + 自动生成回复草稿。
import openai
import imaplib
import email
from email.header import decode_header
# 邮件分类函数
def classify_email(subject, body):
prompt = f"""将以下邮件分类为:技术咨询/商务合作/投诉/其他
邮件主题:{subject}
邮件内容:{body[:500]} # 截取前500字符
分类结果(只需返回分类名称):"""
response = openai.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content.strip()
# 获取未读邮件
def process_inbox():
mail = imaplib.IMAP4_SSL("imap.example.com")
mail.login("your@email.com", "password")
mail.select("INBOX")
_, messages = mail.search(None, "UNSEEN")
for msg_id in messages[0].split():
_, msg_data = mail.fetch(msg_id, "(RFC822)")
msg = email.message_from_bytes(msg_data[0][1])
subject = decode_header(msg["Subject"])[0][0]
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() == "text/plain":
body = part.get_payload(decode=True).decode()
else:
body = msg.get_payload(decode=True).decode()
category = classify_email(subject, body)
print(f"[{category}] {subject}")
# 根据分类转发或自动回复
if category == "投诉":
print("→ 转接客服主管处理")
elif category == "技术咨询":
print("→ 自动回复:已收到,将在24小时内回复")
elif category == "商务合作":
print("→ 转接销售团队")
mail.logout()
# process_inbox() # 解除注释后运行
效果:邮件处理效率提升5倍,且不会漏掉重要邮件。
案例4:会议录音自动总结
痛点:开完1小时会议,记笔记花了半小时,还容易漏掉关键决策。
方案:使用Whisper语音转文字 + LLM总结。
import whisper
import openai
def transcribe_and_summarize(audio_file):
"""识别录音并生成会议纪要"""
# 1. 语音转文字
model = whisper.load_model("base")
result = model.transcribe(audio_file, language="zh")
transcript = result["text"]
# 2. LLM总结
prompt = f"""请根据以下会议录音转写,生成结构化的会议纪要:
要求格式:
## 会议概要
- 时间:{获取会议时间}
- 参与人:(根据上下文识别)
## 讨论要点
- 逐条列出关键讨论内容
## 决策与结论
- 记录了哪些决定
## 待办事项
- 责任人|事项|截止日期
录音内容:
{transcript}
会议纪要:"""
response = openai.chat.completions.create(
model="deepseek-chat",
messages=[{"role": "user", "content": prompt}]
)
return response.choices[0].message.content
# transcribe_and_summarize("会议录音.mp3")
效果:1小时会议,5分钟完成纪要整理,关键信息零遗漏。
三、自动化工作流设计原则
- 80/20法则:只自动化那些重复频率高、规则明确的任务。不常见的任务手动处理更划算。
- 人机协同:AI处理初稿和分类,人做最终审核和决策。不要全自动不审核。
- 渐进式投入:先从1个最痛点开始,跑通后再扩展。一口吃不成胖子。
- 关注维护成本:脚本写1小时,每周省1小时,一年就是50倍收益。但需要额外花时间维护的自动化要谨慎。
四、推荐的自动化搭台工具
| 工具 | 适用场景 | 学习成本 |
|---|---|---|
| Python脚本 | 数据处理、文件操作 | 中等 |
| n8n | 多系统工作流编排 | 低 |
| Make (Integromat) | SaaS应用联动 | 低 |
| Zapier | 非技术人员快速搭建 | 最低 |
| AutoHotkey | Windows桌面自动化 | 中等 |
五、总结
AI办公自动化不是未来,而是现在就可以做的事情。关键是:
– 选一个你最痛、最烦的重复工作
– 用Python + LLM花1-2小时写个脚本
– 跑通后每天省下30分钟
30分钟一天,一年就是182个小时——等于多出整整一个月的工作时间。把这些时间用在真正有价值的事情上,这就是AI给我们最大的红利。
本文为原创教程,发布于科学小舟AI使用skills板块。
