我正在尝试azure情绪分析api
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
credential = AzureKeyCredential("<api_key>")
endpoint="https://<region>.api.cognitive.microsoft.com/"
text_analytics_client = TextAnalyticsClient(endpoint, credential)
documents = [
"I did not like the restaurant. The food was too spicy.",
"The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
"The food was yummy. :)"
]
response = text_analytics_client.analyze_sentiment(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
print("Overall sentiment: {}".format(doc.sentiment))
print("Scores: positive={}; neutral={}; negative={} \n".format(
doc.confidence_scores.positive,
doc.confidence_scores.neutral,
doc.confidence_scores.negative,
))这段代码运行得很好,但是我想读取一个df列,获取文本情感并创建一个列来存储文本情感,你知道我该怎么做吗?我尝试过传递documents = df['column_name']和df[I],但得到了错误
发布于 2021-06-24 04:30:53
下面的代码应该提供一个包含两列的dataframe,一列用于保存文档文本,另一列用于保存相应的情感:
from azure.core.credentials import AzureKeyCredential
from azure.ai.textanalytics import TextAnalyticsClient
import pandas as pd
from tabulate import tabulate
documents = [
"I did not like the restaurant. The food was too spicy.",
"The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to.",
"The food was yummy. :)"
]
df = pd.DataFrame()
df["Documents"] = documents
response = text_analytics_client.analyze_sentiment(documents, language="en")
result = [doc for doc in response if not doc.is_error]
for doc in result:
df["Sentiment"] = doc.sentiment
print("Overall sentiment: {}".format(doc.sentiment))
print("Scores: positive={}; neutral={}; negative={} \n".format(
doc.confidence_scores.positive,
doc.confidence_scores.neutral,
doc.confidence_scores.negative,
))
print(tabulate(df, showindex=False, headers=df.columns))输出:
Documents Sentiment
------------------------------------------------------------------------------------------------------ -----------
I did not like the restaurant. The food was too spicy. positive
The restaurant was decorated beautifully. The atmosphere was unlike any other restaurant I've been to. positive
The food was yummy. :) positivehttps://stackoverflow.com/questions/68105255
复制相似问题