原書的 12/sentiment.py 使用 xlwings 逐列讀取 travels.xlsm 的 Review (EN),呼叫 OpenAI model 判定 positive/negative/mixed,並把結果寫到 H 欄。
xw.Book.caller() 連到 Excel。main() 選第一張 worksheet,先設定 H1 = "Sentiment",從 row 2 開始迴圈讀 G 欄。
| 設定 | 原書值 |
|---|---|
| Review source | Column G |
| Output | Column H / Sentiment |
| Labels | positive/negative/mixed |
| Model | gpt-4.1-mini |
Prompt 明確要求:Classify the sentiment of this travel review as 'positive', 'negative', or 'mixed'. Return only the single word label. Python 以 client.responses.create(...) 呼叫 model,strip() 後寫入 H{row}。
可從 command line 執行 python sentiment.py;也可用 VBA:Application.Run "xlwings.RunPython", "import sentiment; sentiment.main()" 從 Excel 觸發。
Figure 12-10 顯示 workbook 多出 Sentiment 欄。A 檔正文沒有逐筆列出 10 個 sentiment labels,因此本頁不補造。
逐列 API call 容易理解,但會有 latency/cost,而且分類輸出仍需 sample validation。若 review 中途有空白,原書 if review is None: break 會直接停止迴圈,因此資料完整性也會影響處理範圍。