【Python数据分析五十个小案例】使用自然语言处理(NLP)技术分析 Twitter 情感

博客主页:小馒头学python

本文专栏: Python爬虫五十个小案例

专栏简介:分享五十个Python爬虫小案例

项目简介

什么是情感分析

情感分析(Sentiment Analysis)是文本分析的一部分,旨在识别文本中传递的情感信息,例如正面、负面或中立情绪。

为什么选择 Twitter 数据

数据丰富:Twitter 上每天产生数百万条推文,内容多样。

即时性:适合实时分析。

公开可用:提供 API 可轻松访问。

NLP 在情感分析中的作用

通过 NLP 技术,可以将非结构化文本数据转化为结构化信息,提取情绪、关键词等有价值的内容。

项目准备

环境配置

  • 操作系统:Windows/Linux/MacOS
  • Python:版本 3.8+
  • 库依赖:tweepy,nltk,scikit-learn,pandas,matplotlib,seaborn,TensorFlow
python 复制代码
pip install tweepy nltk scikit-learn pandas matplotlib seaborn tensorflow

必备库介绍

  • tweepy:用于访问 Twitter API
  • nltk:提供 NLP 工具,如分词、停用词处理
  • scikit-learn:模型训练与评估
  • TensorFlow:深度学习框架

数据获取与预处理

获取 Twitter 数据

python 复制代码
import tweepy

# 设置 API 密钥
api_key = "YOUR_API_KEY"
api_secret = "YOUR_API_SECRET"
access_token = "YOUR_ACCESS_TOKEN"
access_token_secret = "YOUR_ACCESS_TOKEN_SECRET"

# 连接 Twitter API
auth = tweepy.OAuthHandler(api_key, api_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

# 获取推文数据
tweets = api.search_tweets(q="AI", lang="en", count=100)
tweet_texts = [tweet.text for tweet in tweets]

print(tweet_texts[:5])  # 打印前5条推文

可视化

数据分布分析

python 复制代码
import pandas as pd
from collections import Counter

# 加载推文数据
df = pd.DataFrame(tweet_texts, columns=["Tweet"])
df['Length'] = df['Tweet'].apply(len)

# 分析推文长度分布
print(df['Length'].describe())

数据可视化示例

python 复制代码
import matplotlib.pyplot as plt
import seaborn as sns

# 可视化推文长度分布
sns.histplot(df['Length'], bins=20, kde=True)
plt.title("Tweet Length Distribution")
plt.xlabel("Length")
plt.ylabel("Frequency")
plt.show()

自然语言处理管道

数据清洗与预处理

python 复制代码
import re
import nltk
from nltk.corpus import stopwords

nltk.download('stopwords')
stop_words = set(stopwords.words('english'))

def clean_text(text):
    text = re.sub(r"http\S+", "", text)  # 移除URL
    text = re.sub(r"@\w+", "", text)    # 移除@用户
    text = re.sub(r"#", "", text)       # 移除话题符号
    text = re.sub(r"[^a-zA-Z]", " ", text)  # 保留字母
    text = text.lower()                # 转为小写
    text = " ".join(word for word in text.split() if word not in stop_words)  # 移除停用词
    return text

df['Cleaned_Tweet'] = df['Tweet'].apply(clean_text)

词向量化

python 复制代码
from sklearn.feature_extraction.text import TfidfVectorizer

vectorizer = TfidfVectorizer(max_features=1000)
X = vectorizer.fit_transform(df['Cleaned_Tweet']).toarray()

模型训练与评估

模型选择

python 复制代码
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report

# 模拟情感标签
import numpy as np
df['Sentiment'] = np.random.choice(['Positive', 'Negative', 'Neutral'], len(df))

# 数据拆分
X_train, X_test, y_train, y_test = train_test_split(X, df['Sentiment'], test_size=0.2, random_state=42)

# 训练模型
model = RandomForestClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

# 评估模型
print(classification_report(y_test, y_pred))

案例展示与结果分析

情感分类结果可视化

python 复制代码
from sklearn.metrics import confusion_matrix
import seaborn as sns

cm = confusion_matrix(y_test, y_pred, labels=['Positive', 'Negative', 'Neutral'])
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Positive', 'Negative', 'Neutral'], yticklabels=['Positive', 'Negative', 'Neutral'])
plt.title("Confusion Matrix")
plt.xlabel("Predicted")
plt.ylabel("True")
plt.show()

示例 Tweet 的情感预测

python 复制代码
sample_tweets = ["I love this product!", "This is the worst service ever."]
sample_cleaned = [clean_text(tweet) for tweet in sample_tweets]
sample_vectorized = vectorizer.transform(sample_cleaned).toarray()

print(model.predict(sample_vectorized))

总结

社交媒体情感分析利用自然语言处理(NLP)技术对平台上的用户文本进行情感分类,旨在识别推文或评论中的情绪倾向,如正面、负面或中立。这项技术在商业、舆情监控和社会研究等领域有广泛应用。例如,通过分析 Twitter 上的推文,企业可以了解用户对其品牌或产品的情感反应,从而优化市场营销策略。情感分析过程通常包括数据采集、文本清洗、特征提取以及模型训练等步骤,而现代深度学习模型(如 LSTM 和 BERT)在准确性和情感分类能力上表现尤为出色,感兴趣的同学可以自行去看看

若感兴趣可以访问并订阅我的专栏:Python数据分析五十个小案例

相关推荐
databook6 分钟前
Manim实现闪光轨迹特效
后端·python·动效
Juchecar1 小时前
解惑:NumPy 中 ndarray.ndim 到底是什么?
python
用户8356290780511 小时前
Python 删除 Excel 工作表中的空白行列
后端·python
Json_1 小时前
使用python-fastApi框架开发一个学校宿舍管理系统-前后端分离项目
后端·python·fastapi
RestCloud2 小时前
数据传输中的三大难题,ETL 平台是如何解决的?
数据分析·api
数据智能老司机8 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机9 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机9 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机9 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i9 小时前
drf初步梳理
python·django