ハンズオンをやりながら、そういやCognitiveが返す複合型の取り扱いってPythonでどうすっかな、という疑問が湧き。
それっぽいクラスはSDKにあるんだけど、これはazure_aiエクステンションが返すものとは合致しないので、以下のようにするしか無いかなぁ…
#!/usr/bin/env python3.11
import psycopg as pg
from psycopg.rows import dict_row, namedtuple_row
class SentimentResult:
def __init__(self, sentiment: str, positive: float, neutral: float, negative: float):
self.sentiment = sentiment
self.positive = positive
self.neutral = neutral
self.negative = negative
def __str__(self):
return f"Sentiment: {self.sentiment}, Positive: {str(self.positive)}, Neutral: {str(self.neutral)}, Negative: {str(self.negative)}"
with pg.connect(
host = 'psql-learn-japaneast-xxxxxxxx.postgres.database.azure.com',
port = 5432,
dbname = 'rentals',
user = 'pgAdmin',
password = 'password'
) as conn:
with conn.cursor(row_factory = namedtuple_row) as cur:
cur.execute("SELECT id, comments, azure_cognitive.analyze_sentiment(comments, 'en') AS sentiment FROM reviews WHERE id = 1")
row = cur.fetchone()
if row is not None:
res = SentimentResult(*row.sentiment.replace("(", "").replace(")", "").split(','))
print(f"Sentiment: {res}")