我正在尝试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]
,但我得到错误
以下代码应该为您提供一个包含两列的数据帧,一列用于保存文档文本,另一列用于存储相应的情感:
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. :) positive