import openpyxl
import openai
from openpyxl import Workbook
# 请替换为您的OpenAI API密钥
api_key = ""
openai.api_key = api_key
# 读取xlsx文件
def read_xlsx_column(file_path, column_index):
# 打开工作簿
workbook = openpyxl.load_workbook(file_path)
# 选择第一个工作表
sheet = workbook.active
# 读取指定列的数据
data = []
for row in sheet.iter_rows(min_row=1, min_col=column_index, max_col=column_index):
cell_value = row[0].value
if cell_value is not None:
data.append(str(cell_value))
return data
# 设置文件路径和列索引
file_path = 'questions.xlsx'
column_index = 2
def ask_gpt(question,model):
completion = openai.ChatCompletion.create(
model=model,
messages=[
{"role": "user", "content": question},
]
)
answer = completion.choices[0].message['content']
return answer
# 读取第二列数据并添加到字符串数组中
column_data = read_xlsx_column(file_path, column_index)
questions=column_data[170:249]
print("questions num:")
print(len(questions))
# 创建一个新的Excel工作簿
workbook = Workbook()
sheet = workbook.active
sheet.title = "问题与答案"
# 添加表头
sheet["A1"] = "问题"
sheet["B1"] = "gpt-4"
sheet["C1"] = "gpt-3.5-turbo"
# 获取答案并将问题和答案添加到Excel表格中
row = 2
for question in questions:
try:
gpt4answer = ask_gpt(question, "gpt-4")
except Exception as e:
print(f"GPT-4 request for question {question} failed with error: {e}")
gpt4answer = "Error: 请求失败"
try:
gpt3answer = ask_gpt(question, "gpt-3.5-turbo")
except Exception as e:
print(f"GPT-3.5-turbo request for question {question} failed with error: {e}")
gpt3answer = "Error: 请求失败"
sheet.cell(row=row, column=1, value=question)
sheet.cell(row=row, column=2, value=gpt4answer)
sheet.cell(row=row, column=3, value=gpt3answer)
row += 1
print(row)
# 保存Excel文件
try:
workbook.save("questionsandanswers6.xlsx")
print("success")
except Exception as e:
print(f"Failed to save the workbook with error: {e}")