import requests
import pandas as pd
# https://dashscope.console.aliyun.com/billing 查看调用模型的计费
# https://dashscope.console.aliyun.com/apiKey 获取API密钥
# 设置调用参数,生成回答
def chatgpt(prompt):
headers = {
'Authorization': '你的密钥', # 这里替换你的密钥
'Content-Type': 'application/json',
}
json_data = {
'model': 'qwen-max', #通义千问最高模型收费很贵
'input': {
'messages': [
{
'role': 'system',
'content': '你是一个情感分析模型', #定义角色
},
{
'role': 'user',
'content': str(prompt),
},
],
},
'parameters': {},
}
try:
response = requests.post(
'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation',
headers=headers,
json=json_data,
)
content = response.json()
last_text = content['output']['text']
return last_text
except Exception as e:
print(f"Error: {e}")
return None
#定义要读取多少行,修改文件路径
df = pd.read_excel(r"你的路径\data.xlsx").iloc[100:200,:]
sent_list = []
rensponse_list=[]
for index, row in df.iterrows():
review = row['评论内容']
prompt = f"文本: '{review}'. 任务:分析这条评论对转基因食品的支持度,回复0-1之间的浮点数。特别注意考虑是否含有讽刺意味,因为留言者很可能会讽刺那些反对转基因食品的人。如果含有讽刺意味则要提高支持度。结构化输出:支持度、理由"
sentiment = chatgpt(prompt)
print(index+1, '|', sentiment, "\n", "—"*10, "\n")
rensponse_list.append(sentiment[12:])
sent_list.append(str(sentiment)[4:7])
sent_list #检查输出是否有空值,有的话要补,因为大模型可能卡机
df['LLM支持度']=sent_list
df['LLM回复语']=rensponse_list
outfile=df[['LLM支持度','LLM回复语']]
outfile.to_csv('情感分析.csv',index=True)