如何将情感分析Python代码转为可接收用户输入的Flask API?
实现支持用户输入的Flask情感分析API
先给你一套完整的可运行代码,基于需求改造,包含输入接收、处理和结果返回:
from flask import Flask, request, jsonify # 替换成你已有的情感分析函数 def analyze_sentiment(text): # 这里是示例逻辑,替换为你的实际情感分析代码 positive_words = ["好", "棒", "开心", "满意"] negative_words = ["坏", "糟", "难过", "失望"] pos_count = sum(1 for word in positive_words if word in text) neg_count = sum(1 for word in negative_words if word in text) if pos_count > neg_count: return {"sentiment": "positive", "confidence": pos_count / (pos_count + neg_count)} elif neg_count > pos_count: return {"sentiment": "negative", "confidence": neg_count / (pos_count + neg_count)} else: return {"sentiment": "neutral", "confidence": 0.5} app = Flask(__name__) # 定义接收输入的API路由,使用POST方法 @app.route('/analyze', methods=['POST']) def sentiment_api(): # 读取客户端发送的JSON格式输入 data = request.get_json() # 校验输入是否合法 if not data or 'text' not in data: return jsonify({"error": "请提供要分析的文本字段'text'"}), 400 user_input = data['text'] # 调用情感分析函数处理输入 result = analyze_sentiment(user_input) # 返回JSON格式的分析结果 return jsonify(result) if __name__ == '__main__': app.run(debug=True)
关键部分说明:
- 请求方式:用
POST而非GET,避免URL长度限制和输入内容泄露的问题 - 输入读取:
request.get_json()用于获取客户端发送的JSON数据,需确保请求头包含Content-Type: application/json - 错误处理:校验输入是否包含必填的
text字段,若缺失则返回400错误提示,避免程序异常 - 结果返回:
jsonify()会把分析结果转为标准JSON响应,方便前端或其他服务解析
测试方法:
用curl命令快速测试:
curl -X POST -H "Content-Type: application/json" -d '{"text": "今天天气真好,我很开心"}' http://localhost:5000/analyze
返回结果示例:
{"confidence": 1.0, "sentiment": "positive"}
也可以用Postman发送POST请求,在Body中选择raw-JSON格式,输入{"text": "你的测试文本"}即可。
适配现有代码:
只需要把示例中的analyze_sentiment函数替换成你自己的情感分析代码即可,确保你的函数接收一个字符串参数,返回可转为JSON的字典或对象。
内容的提问来源于stack exchange,提问作者Faiz Hassan
相关产品推荐
相关产品推荐

