import pandas as pd
import requests
import json
import time
data_all = pd.read_excel('144基金贴吧评论.xlsx')
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=【AK】&client_secret=【SK】'
#获取token
url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token={}'.format(
json.loads(requests.post(host).text)['access_token'])
with open('result.txt', 'a', encoding='utf-8') as f:
for i in range(167724,data_all.shape[0]):
if i % 5 == 0:
time.sleep(1)
if i % 20 == 0:
url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/sentiment_classify?charset=UTF-8&access_token={}'.format(
json.loads(requests.post(host).text)['access_token'])
print(str(data_all.shape[0]) + ':' + str(i))
data = {
'text': data_all.iloc[i, 2]
}
try:
data = json.dumps(data)
res = json.loads(requests.post(url, data=data).text)
f.write(str(res['text']) + ',' + str(res['items'][0]['positive_prob']) + ',' + str(
res['items'][0]['negative_prob']) + ',' + str(res['items'][0]['negative_prob']) + '\n')
except:
f.write('NULLTEXT' + ',' + '' + ',' + '' + ',' + '' + '\n')