import openai
import os
openai.api_key = "填写你的openai-key"
conversation=[{"role": "system", "content": "You are a helpful assistant."}]
max_history_len = 20
first_message = None
dir = r'E:\知识库\python学习\自动化-selenium\chatgpt\文章处理\时事新闻文章抓取\intput' #要改写的文档所在目录
#获取目录列表
list_dir = os.listdir(dir)
#打印目录列表
print(list_dir)
#遍历目录列表
for i in range(len(list_dir)):
try:
title = list_dir[i] #要改写的文档文件名称,新建一个intput目录,文档放在intput目录下
print(title) #打印文档名称
#这里要读取两次,第一次是计算循坏所需要的次数,第二次读取原文
f = open("./intput/{}".format(title),'r',encoding= 'utf-8') #
s = len(f.read()) // 400
f.close()
f = open("./intput/{}".format(title),'r',encoding= 'utf-8')
for i in range(s+1):
content = f.read(400)
print('这是原文:', content + "\n")
conversation = [{"role": "system", "content": "You are a helpful assistant."}]
prompt = '根据以下段落,改写成新闻稿,输出中文并保留重点:' + content #content为原文
if first_message is None:
first_message = prompt # 存储第一句话
conversation.append({"role": "user", "content": prompt})
prompt_history = "\n".join([f"{i['role']}: {i['content']}" for i in conversation])
prompt = f"Conversation history:\n{first_message}\n{prompt_history}"
if len(conversation) > max_history_len:
conversation = conversation[-max_history_len:]
# 将第一句话添加到生成的 prompt 中
conversation.insert(0, {"role": "user", "content": first_message})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=conversation,
temperature=2,
max_tokens=2048,
top_p=0.9
)
conversation.append({"role": "assistant", "content": response['choices'][0]['message']['content']}) # 将上一次会话信息返回给chatgpt,可省略
message = response['choices'][0]['message']['content'] + "\n"
print('这是改写后的文章:', message)
#改写的结果都保存为output/xxx文件,先新建一个output目录
with open("./output/{}".format(title), "a") as f2:
f2.write(message)
f2.close()
except:
print('出错了,跳过当前文本')
i += 1
print('转换完成,请查看你的文章')
- 1
- 2
- 3
前往页