赞
踩
目录
开通NLP服务后,获赠5万次免费调用。
必填参数是Text,即待分析的文本(仅支持UTF-8格式,不超过200字),类型是String。
复制代码后,定义get_sentiment函数,并设置返回结果为字典类型,以便于后续分析使用。
- 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
- from tencentcloud.nlp.v20190408 import nlp_client, models
- def get_sentiment(text):
- try:
- # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
- cred = credential.Credential("SecretId", "SecretKey")
- # 实例化一个http选项,可选的,没有特殊需求可以跳过
- httpProfile = HttpProfile()
- httpProfile.endpoint = "nlp.ap-shanghai.tencentcloudapi.com"
- # 实例化一个client选项,可选的,没有特殊需求可以跳过
- clientProfile = ClientProfile()
- clientProfile.httpProfile = httpProfile
- # 实例化要请求产品的client对象,clientProfile是可选的
- client = nlp_client.NlpClient(cred, "", clientProfile)
- # 实例化一个请求对象,每个接口都会对应一个request对象
- req = models.AnalyzeSentimentRequest()
- params = {
- "Text": text
- }
- req.from_json_string(json.dumps(params))
- # 返回的resp是一个AnalyzeSentimentResponse的实例,与请求对象对应
- resp = client.AnalyzeSentiment(req)
-
- except TencentCloudSDKException as err:
- print(err)
-
- return json.loads(resp.to_json_string())
-
- get_sentiment(text='your text')
中国大陆地区的用户可以使用国内镜像源以提高下载速度,例如:
pip install -i https://mirrors.tencent.com/pypi/simple/ --upgrade tencentcloud-sdk-python
- import pandas as pd
-
- # 1. 打开文件
- df = pd.read_excel("评论情感分析.xlsx")
-
- # 2. 写循环,进行情感分析
- for index in range(1000):
- comment = df.loc[index, "评论"][:200]
- sentiment_result = get_sentiment(comment)
-
- # 3. 新增'Positive','Neutral', 'Negative', 'Sentiment', 'RequestId'五列
- df.loc[index, 'Positive'] = sentiment_result['Positive']
- df.loc[index, 'Neutral'] = sentiment_result['Neutral']
- df.loc[index, 'Negative'] = sentiment_result['Negative']
- df.loc[index, 'Sentiment'] = sentiment_result['Sentiment']
- df.loc[index, 'RequestId'] = sentiment_result['RequestId']
-
- # 4. 每写入一个循环,print一句提示
- print(f"已处理第 {index + 1} 行评论。")
-
- # 5. 将情感分析结果写入文件
- df.to_excel("评论情感分析.xlsx", index=False)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。