python
from textblob import TextBlob
import mysql.connector
连接到 MySQL 数据库
db = mysql.connector.connect(
host=localhost,
user=your_username,
password=your_password,
database=your_database
)
cursor = db.cursor()
查询未分析的文本
query = SELECT id, text_content FROM texts WHERE id NOT IN (SELECT text_id FROM sentiment_analysis_results)
cursor.execute(query)
texts = cursor.fetchall()
遍历文本并进行情感分析
for text_id, text_content in texts:
blob = TextBlob(text_content)
sentiment_score = blob.sentiment.polarity
sentiment_label = 'positive' if sentiment_score 0 else 'negative' if sentiment_score < 0 else 'neutral'
方法 2: 使用云服务或 API
如果不想自己搭建模型,可以使用现成的情感分析 API,例如:
Google Cloud Natural Language API
IBM Watson Tone Analyzer
Microsoft Azure Text Analytics
调用这些 API 后,将返回的情感分析结果插入到 MySQL 数据库中。
4、查询和统计
完成情感分析后,可以使用 SQL 查询对结果进行统计分析。例如:
查询所有正面情感的文本
sql
SELECT t.text_content, s.sentiment_score
FROM texts t
JOIN sentiment_analysis_results s ON t.id = s.text_id
WHERE s.sentiment_label = 'positive';
统计每种情感的数量
sql
SELECT sentiment_label, COUNT(*) AS count
FROM sentiment_analysis_results
GROUP BY sentiment_label;