当前位置:   article > 正文

Python 调用腾讯云自然语言处理接口之情感分析、关键词提取等_腾讯api 情感分析

腾讯api 情感分析

1 开通NLP服务

自然语言处理

需要进行个人认证

在这里插入图片描述
拥有腾讯云的实名账号,开通后每天有50万次免费调用,超过次数后才会收费。
在这里插入图片描述
下面有一个快速使用,也有详细的说明怎么调用接口

快速使用

在这里插入图片描述

打开工具
在这里插入图片描述
这里也可以快速使用,这里我暂时不这么做

2 获取安全凭证

进入

腾讯自然语言处理平台

在这里插入图片描述
进入右上角的控制台

在这里插入图片描述
选择Python

在这里插入图片描述
这里面有很详细的教程

在这里插入图片描述

安全凭证包含 SecretId 及 SecretKey 两部分。SecretId 用于标识 API 调用者的身份,SecretKey 用于加密签名字符串和服务器端验证签名字符串的密钥。

新建密钥

在这里插入图片描述
即可获得安全凭证
在这里插入图片描述

注意:安全凭证代表账号身份和所拥有的权限,等同于登录密码,切勿泄露他人。

3 获取调用地址

调用地址(endpoint)一般形式为*.tencentcloudapi.com,产品的调用地址有一定区别,例如,云服务器的调用地址为cvm.tencentcloudapi.com。

这里的形式如下

nlp.tencentcloudapi.com

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
填入刚刚申请的密钥以及必要参数,之后参数会自动在右侧的python代码中出现
在这里插入图片描述
在这里插入图片描述

4 安装 SDK

在命令行中执行以下命令,安装 Python SDK。

# 以腾讯源为例 
# 源地址后为所要安装的包:tencentcloud-sdk-python
pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
  • 1
  • 2
  • 3

在这里插入图片描述

5 在Python中调用

复制刚才的python代码到编辑器中,简单的修改

在这里插入图片描述

使用 apply 将 dataframe 中内容为 list 的列拆分为多列

参考:Pandas 的这个知识点,估计 80% 的人都得挂!

在这里插入图片描述

完整代码

数据

import json
from tencentcloud.common import credential
# 导入可选配置项
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的 client models。
from tencentcloud.nlp.v20190408 import nlp_client, models

def get_sentiment(text):
    try: 
        # 实例化一个认证对象,入参需要传入腾讯云账户 secretId,secretKey
        cred = credential.Credential("AKID***", "***")  
        
        # 实例化一个 http 选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        httpProfile.endpoint = "nlp.tencentcloudapi.com"
        
        # 实例化一个 client 选项,可选的,没有特殊需求可以跳过。
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        
        # 实例化要请求产品 (以 cvm 为例) 的 client 对象
        # client = cvm_client.CvmClient(cred, "ap-shanghai")
        client = nlp_client.NlpClient(cred, "ap-guangzhou", clientProfile) 
        
        # 实例化一个请求对象
        # req = models.DescribeZonesRequest()
        req = models.SentimentAnalysisRequest()
        
        # 这里还支持以标准 json 格式的 string 来赋值请求参数的方式。
        params = {
            "Text": text,
            
            # Flag 选填 待分析文本所属的类型
            # 仅当输入参数Mode取值为2class时有效(默认取4值)
            # 1、商品评论类 2、社交类 3、美食酒店类 4、通用领域类
            #'Flag' :2,
            
            # Mode 选填 情感分类模式选项,
            # 可取2class或3class(默认值为2class) 
            # 1、2class:返回正负面二分类情感结果 2、3class:返回正负面及中性三分类情感结果
            "Mode": "3class"
        }
        req.from_json_string(json.dumps(params))
        
        # 通过 client 对象调用想要访问的接口,需要传入请求对象
        resp = client.SentimentAnalysis(req) 
        # 输出 json 格式的字符串回包
        j = json.loads(resp.to_json_string())
        
        return [j['Positive'],j['Negative'],j['Neutral'],j['Sentiment']]
    except TencentCloudSDKException as err: 
        print(err)
        

# get_sentiment(text = '你吃过了吗')

import pandas as pd
import numpy as np
import os
import jieba 

os.chdir(r'C:\Users\Administrator\Desktop')
# 读取csv文件获取数据并存储到列表中
df = pd.read_excel('处理好的弹幕数据.xlsx')
data = df['弹幕'][:100].to_frame()

data['情感分析'] = data['弹幕'].apply(get_sentiment)

# 使用 apply 将 dataframe 中内容为 list 的列拆分为多列
data[['积极','中立','消极','情感倾向']] = data['情感分析'].apply(pd.Series)
data = data.drop('情感分析',axis=1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

数据可视化呈现
在这里插入图片描述

emo = data.groupby('情感倾向')['弹幕'].count()
'''
情感倾向
negative    13
neutral     48
positive    39
Name: 弹幕, dtype: int64
'''
regions = emo.index.to_list()
values = emo.to_list()

import numpy as np
import matplotlib.pyplot as plt

plt.figure(figsize=(6,5),dpi=150)
plt.rcParams['font.sans-serif']=['KaiTi']
plt.rcParams['axes.unicode_minus']=False

plt.pie(values,labels=regions,radius=1.0,
        wedgeprops=dict(width=0.4,edgecolor='w'), textprops={'fontsize': 12},colors=['#FFCC99','#CCFF66','#99CCFF'])
plt.show()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

注意:每天只有50万次免费调用,超过需要收费的

最后还有一点就是,我的数据仅仅才一万出头,使用 apply 跑代码,运行的时候报错

在这里插入图片描述

这个问题,不知道是不是数据量太大了,还是太频繁了

我用100条数据,虽然成功了,但也运行了一分钟左右…

6 其他接口

除了情感分析接口外,还有很多其他自然语言处理接口

在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/531714
推荐阅读
相关标签
  

闽ICP备14008679号