# AI 工具集
安装:
pip install python-office独立安装:pip install poai
AI编程课程👉点我直达
python-office 集成了多种 AI 能力,提供 AI 对话、绘图、翻译等功能,让办公智能化。
# 1、AI 对话
与 AI 大模型进行智能对话,解答问题、生成内容。
# 基本用法
import office
# AI 对话
result = office.ai.chat(
message='你好,请介绍一下 Python'
)
print(result)
# 参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
message | str | 是 | 对话内容 |
api_key | str | 否 | API Key(未提供则使用默认配置) |
# 完整示例
import office
# 简单的问答
response = office.ai.chat(
message='帮我写一段 Python 读取 Excel 的代码',
api_key='your-api-key'
)
print(response)
# 2、AI 绘图
根据文字描述生成图片。
# 基本用法
import office
# AI 绘图
result = office.ai.draw(
prompt='一只可爱的橘猫在晒太阳'
)
print(result)
# 参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
prompt | str | 是 | 绘图描述 |
size | str | 否 | 图片尺寸,默认 1024x1024 |
# 完整示例
import office
# 生成风景图
result = office.ai.draw(
prompt='一幅山水画,云雾缭绕,古风建筑',
size='1024x1024'
)
# 保存图片
if result.get('success'):
image_url = result['url']
print(f'图片生成成功:{image_url}')
# 3、AI 翻译
多语言文本翻译。
# 基本用法
import office
# 翻译
result = office.ai.translate(
text='Hello, how are you?',
from_lang='en',
to_lang='zh'
)
print(result)
# 参数说明
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
text | str | 是 | 要翻译的文本 |
from_lang | str | 否 | 源语言,默认自动检测 |
to_lang | str | 是 | 目标语言 |
# 常用语言代码
| 代码 | 语言 | 代码 | 语言 |
|---|---|---|---|
zh | 中文 | en | 英语 |
ja | 日语 | ko | 韩语 |
fr | 法语 | de | 德语 |
es | 西班牙语 | ru | 俄语 |
# 完整示例
import office
# 批量翻译
texts = [
'Hello World',
'Python is great',
'Thank you very much'
]
for text in texts:
result = office.ai.translate(
text=text,
from_lang='en',
to_lang='zh'
)
print(f'{text} → {result}')
# 4、综合应用示例
# 智能客服助手
import office
def smart_customer_service(question):
"""智能客服"""
# 判断问题类型
if '价格' in question:
return '我们的产品价格请查看官网:xxx.com'
elif '快递' in question:
return '您的订单已发货,预计3-5天到达'
elif '退货' in question:
return '退货请联系客服,提供订单号即可办理'
else:
# 使用 AI 回答
return office.ai.chat(question)
# 测试
print(smart_customer_service('你们的产品多少钱?'))
# 文档自动翻译
import office
def translate_document(input_file, output_file, target_lang='zh'):
"""批量翻译文档"""
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
# 翻译
result = office.ai.translate(
text=content,
from_lang='en',
to_lang=target_lang
)
# 保存
with open(output_file, 'w', encoding='utf-8') as f:
f.write(result)
print(f'翻译完成:{output_file}')
# 使用
translate_document('english.txt', 'chinese.txt')
# 5、注意事项
⚠️ 使用提示:
- 使用 AI 功能需要相应的 API Key 或网络连接
- AI 绘图可能需要较长时间,请耐心等待
- 翻译功能支持多种语言,但不是所有语言组合都可用
- 请遵守 AI 服务的使用条款
# 相关课程
# 联系作者
