主要通过官方api文档使用说明再结合网上的一些碎片化代码实现。
使用方法简单暴力,在excel表格第一列输入你的关键词,保存,运行此代码选择该文档即可生成word文档。
如果要保存到txt,excel这些理论上也可自己更改代码实现。
还可以对代码进行一些优化,比如对已生辰内容的关键词增加标记,后续不再重复读取等。
需要用到的火山引起依赖库:https://www.123865.com/s/TKR5Vv-vGu5v
[Python] 纯文本查看 复制代码import os
import pandas as pd
from tkinter import Tk, filedialog
from docx import Document
from concurrent.futures import ThreadPoolExecutor, as_completed
from volcenginesdkarkruntime import Ark
def test_chat(client, model, keyword):
try:
completion = client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
{"role": "user", "content": keyword},
],
)
content = completion.choices[0].message.content
return content
except Exception as e:
print(f"Error during chat: {e}")
return None
def generate_docx(title, content, output_dir):
doc = Document()
doc.add_heading(f"{title}", level=1)
doc.add_paragraph("")
doc.add_heading("", level=2)
doc.add_paragraph(content)
doc.save(os.path.join(output_dir, f"{title}.docx"))
def process_keyword(client, model, keyword, output_dir):
content = test_chat(client, model, keyword)
if content:
# 将 content 中的 * 替换为空
content = content.replace('*', '')
generate_docx(keyword, content, output_dir)
def main():
# 使用Tkinter选择Excel文件和输出文件夹
root = Tk()
root.withdraw() # 隐藏主窗口
excel_file = filedialog.askopenfilename(title="选择Excel文件", filetypes=[("Excel files", "*.xlsx *.xls")])
output_dir = filedialog.askdirectory(title="选择输出文件夹")
if not excel_file or not output_dir:
print("未选择文件或文件夹")
return
# 读取Excel文件
df = pd.read_excel(excel_file, sheet_name='Sheet1')
# 设置 API Key 作为环境变量
os.environ["ARK_API_KEY"] = "此处填入你的key"
# 初始化 Ark 客户端
client = Ark(
base_url="https://ark.cn-beijing.volces.com/api/v3",
)
model = "此处填入需要调用的model名称"
# 使用 ThreadPoolExecutor 进行多线程处理
with ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(process_keyword, client, model, row[0], output_dir) for index, row in df.iterrows()]
for future in as_completed(futures):
try:
future.result()
except Exception as e:
print(f"Error processing keyword: {e}")
if __name__ == '__main__':
main()