#码力全开·技术π对#使用Cloud Natural Language API,如何在Web应用中实时分析用户评论情感?



GCP
key_3_feng
5天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
周周的奇妙编程
周周的奇妙编程

在Web应用中使用Cloud Natural Language API 实时分析用户评论情感,可通过前端采集文本、后端调用API实现低延迟情感评分。由于该API不支持浏览器直接调用,需通过服务端代理请求,确保密钥安全。

实现流程

  1. 后端API代理(Node.js示例)
// server.js
const {LanguageServiceClient} = require('@google-cloud/language');
const client = new LanguageServiceClient();

app.post('/analyze-sentiment', async (req, res) => {
  const {content} = req.body;
  const document = {content, type: 'PLAIN_TEXT', language: 'en'};

  try {
    const [result] = await client.analyzeSentiment({document});
    const {score, magnitude} = result.documentSentiment;
    res.json({score, magnitude}); // score: [-1.0, 1.0], magnitude: [0, inf]
  } catch (error) {
    res.status(500).json({error: 'Sentiment analysis failed'});
  }
});
  1. 前端实时交互(React示例)
function ReviewInput() {
  const [sentiment, setSentiment] = useState(null);

  const handleInput = async (e) => {
    const text = e.target.value;
    if (text.length > 10) {
      const res = await fetch('/analyze-sentiment', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({content: text})
      });
      const data = await res.json();
      setSentiment(data.score > 0 ? 'positive' : data.score < 0 ? 'negative' : 'neutral');
    }
  };

  return (
    <textarea onInput={handleInput} placeholder="输入评论..." />
    {sentiment && <Badge variant={sentiment}>{sentiment}</Badge>}
  );
}

情感指标说明

  • Score:情感极性(-1负面 → +1正面)
  • Magnitude:情感强度(0无情绪 → ∞强烈情绪)

结合实时反馈(如输入时动态变色),可提升用户体验与内容审核效率。

分享
微博
QQ
微信https://www.51cto.com/aigc/
回复
2天前
发布
相关问题
提问