调用百度API进行情感分析

# -*- coding: utf-8 -*-
from aip import AipNlp
import csv
import pandas as pd
from pandas.core.frame import DataFrame

APP_ID = '******'
API_KEY = '888888888'
SECRET_KEY = '88888888'
client = AipNlp(APP_ID, API_KEY, SECRET_KEY)
def output():
    urls = []
    with open('redio11.csv', "r") as f:
        reader = csv.reader(f)
        for row in reader:
            urls.append(row[0])
    return urls

def sentimentClassify():
    x = output()
    i = 1
    pp=[]
    np=[]
    con=[]
    sen=[]
    all={}
    for i in range(10640):
        text = x[i]
        result = client.sentimentClassify(text);
        print(result)
        if "error_code" in result.keys():
            pp.append(" ")
            np.append(" ")
            con.append(" ")
            sen.append(" ")
            all['positive_prob'] = pp
            all['negative_prob'] = np
            all['confidence'] = con
            all['sentiment'] = sen
        else:
            data = result['items']
            items = data[0]
            positive_prob = items['positive_prob']
            pp.append(positive_prob)
            negative_prob = items['negative_prob']
            np.append(negative_prob)
            confidence = items['confidence']

            con.append(confidence)
            sentiment = items['sentiment']
            sen.append(sentiment)
            all['positive_prob'] = pp
            all['negative_prob'] = np
            all['confidence'] = con
            all['sentiment'] = sen
    return all

def add(ulist):
    csv_input = pd.read_csv('redio11.csv', encoding='gbk')
    pp = DataFrame(ulist['positive_prob'])
    csv_input["positive_prob"] = pp
    csv_input.to_csv('redio11.csv', index=False, encoding='gbk')
    np = DataFrame(ulist['negative_prob'])
    csv_input["negative_prob"] = np
    csv_input.to_csv('redio11.csv', index=False, encoding='gbk')
    con = DataFrame(ulist['confidence'])
    csv_input["confidence"] = con
    csv_input.to_csv('redio11.csv', index=False, encoding='gbk')
    sen = DataFrame(ulist['sentiment'])
    csv_input["sentiment"] = sen
    csv_input.to_csv('redio11.csv', index=False, encoding='gbk')

if __name__ == '__main__':
    ALL = sentimentClassify()
    add(ALL)

你可能感兴趣的:(python基础,NLP)