本文介绍两个情感分析的库, 它们可以根据输入的文字内容, 给出一个打分, 这个分数就是对文本的情感的评价(多好/多坏)
使用的库
英文: textblob
中文: snownlp
项目结构
使用场景
区分好评和差评->由此分析产品or视频的好坏/新闻或文章的情绪分析...
用于测试的文本(英文)
mytext.txt
Yesterday I went hiking
On the way up I hurt my knees! It was not good!
We did not have a lot of fun! Now I have some wounds and I am bleeding
I am also a little bit sad
But all in all it was a great experience
mytext_down.txt
I hate this thing
It destroyed my life! I would never buy it again
Word experience yet! This is a bad product
mytext_up.txt
I loved this product
It was great,I will definitely buy more of it
Excellent experience
英文情感分析
运行结果: 1(正向) 0(中性) -1(负面)
from textblob import TextBlob
# 读取本地文件进行分析
with open('mytext.txt', 'r', encoding='utf-8') as f:
text=f.read()
blob = TextBlob(text)
sentiment = blob.sentiment.polarity # 1 ~ -1
print(sentiment)
with open('mytext_up.txt', 'r', encoding='utf-8') as f:
text=f.read()
blob = TextBlob(text)
sentiment = blob.sentiment.polarity # 1 ~ -1
print(sentiment)
with open('mytext_down.txt', 'r', encoding='utf-8') as f:
text=f.read()
blob = TextBlob(text)
sentiment = blob.sentiment.polarity # 1 ~ -1
print(sentiment)
中文情感分析
运行结果: 0~1 越低表示文本越消极
# 中文nlp,仿textblob
from snownlp import SnowNLP
# 读取本地文件进行分析
text=input("输入分析文本: ")
blob = SnowNLP(text)
sentiment = blob.sentiments # 这个库的情绪分 0 ~ 1,越低越消极
print(sentiment)
结合flask, 开放http服务
# flask创建http接口
from flask import Flask, request, jsonify
from flask_cors import CORS
from textblob import TextBlob
# 中文nlp,仿textblob
from snownlp import SnowNLP
# flask
app = Flask(__name__)
CORS(app, resources=r'/*') # 注册CORS, "/*" 允许访问所有api
@app.route("/api/sentiment/analyze/<text>", methods=['get'])
def analyze_short(text):
blob = TextBlob(text) # 情绪评分值
sentiment = blob.sentiment.polarity
return jsonify({"res": sentiment}), 200
# Content-Type: application/json 请求内容格式
@app.route("/api/sentiment/analyze", methods=['post'])
def analyze_large():
blob = TextBlob(request.json.get('text')) # 情绪评分值
sentiment = blob.sentiment.polarity
return jsonify({"res": sentiment}), 200
# 中文情感分析
@app.route("/api/sentiment/analyze/zh_cn/<text>", methods=['get'])
def cn_analyze_short(text):
s = SnowNLP(text) # 情绪评分值
sentiment = s.sentiments # 这个库的情绪分 0 ~ 1,越低越消极
return jsonify({"res": sentiment}), 200
# Content-Type: application/json 请求内容格式
@app.route("/api/sentiment/analyze/zh_cn", methods=['post'])
def cn_analyze_large():
s = SnowNLP(request.json.get('text')) # 情绪评分值
sentiment = s.sentiments # 这个库的情绪分 0 ~ 1,越低越消极
return jsonify({"res": sentiment}), 200
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8763)