Skip to content

Instantly share code, notes, and snippets.

@htlin222
Created March 29, 2023 15:16
Show Gist options
  • Save htlin222/feb5fb9a9d16ed59e42bee2190193b2c to your computer and use it in GitHub Desktop.
Save htlin222/feb5fb9a9d16ed59e42bee2190193b2c to your computer and use it in GitHub Desktop.
# Import necessary libraries
import pandas as pd #用於資料處理的模組
import openai #OpenAI API模組
# Read the Excel file with two columns
df = pd.read_excel('data.xlsx', usecols=['id', 'content']) #從Excel檔案讀取資料到dataframe中,只取'id'和'content'欄位的資料
# Set the OpenAI API key from an environment variable
openai.api_key = "OPENAI_API_KEY" #設置OpenAI API的金鑰
# Iterate over each row in the dataframe
for index, row in df.iterrows(): #迭代dataframe中的每一行
# Form the item for the prompt by concatenating the values in the two columns
item = row['content'] #將'content'欄位的值賦值給item
# Create the prompt with the item
prompt = f"將以下文字翻成中文:\n {item}" #構建提示,使用f-string格式化輸出
print(prompt) #將提示列印出來
# Send the prompt to OpenAI using the Davinci engine
response = openai.Completion.create( #使用OpenAI API,獲取結果
engine="text-davinci-003", #選擇使用Davinci引擎
prompt=prompt, #提示
max_tokens=100, #最大令牌數
n=1, #生成答案的數量
stop=None, #停止條件
temperature=0.7, #生成答案的溫度
).choices[0].text.strip() #取回最佳答案,並去除首尾空格
# Save the response in a new column in the dataframe
df.loc[index, 'Response'] = response #將結果保存到dataframe的新列'Response'中
# Save the updated dataframe to a new Excel file with the third column added
df.to_excel('data_with_responses.xlsx', index=False) #將更新後的dataframe保存到Excel檔案,增加了'Response'列,不包含行索引列
@htlin222
Copy link
Author

Excel 檔案要有以下欄位:

  • id
  • content

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment