基于 NPL的情感分析系统设计与实现(代码)
以下是按照你要求的格式重新组织的内容:
数据预处理是自然语言处理任务的基础环节,对于社交媒体文本数据,其复杂性要求精细处理才能为后续分析提供高质量数据。本研究使用 advanced_preprocess_text
函数来执行这一关键任务,代码如下:
def advanced_preprocess_text(text):
# 去除标点符号
translator = str.maketrans('', '', string.punctuation)
text = text.translate(translator)
# 去除特殊字符
text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', ' ', text)
# 分词
words = jieba.lcut(text)
# 去除停用词
stopwords = set()
try:
with open('stopwords.txt', 'r', encoding='utf-8') as f:
for line in f:
stopwords.add(line.strip())
except FileNotFoundError:
pass
filtered_words = [word for word in words if word not in stopwords]
return ' '.join(filtered_words)
首先,利用 Python 的 string
模块创建字符映射表,通过 translate
方法去除文本中的标点符号,这能有效减少噪声信息,避免标点干扰后续文本特征提取。例如,文本“今天天气真好!”经此处理变为“今天天气真好”。接着,使用正则表达式 re.sub
剔除如特殊符号、乱码等非文字信息,确保文本纯净。随后,调用 jieba
库的 lcut
函数对文本进行分词,将连续语句拆分成单个词语,如“我爱北京天安门”会被切分为“我”“爱”“北京”“天安门”,使得文本能在词语层面深入分析。最后,尝试从 stopwords.txt
文件读取停用词集,过滤掉像“的”“是”“在”等高频但对情感表达贡献小的词汇,若文件未找到则跳过停用词去除步骤。经这些步骤,杂乱的原始文本转化为适宜后续分析的规范形式。
情感分析是核心任务,旨在判断社交媒体文本的情感倾向,本研究借助 SnowNLP
库并结合 multi_dim_sentiment_analysis
和 get_sentiment_category_info
函数实现。
# 根据情感得分返回情感类别和描述信息
def get_sentiment_category_info(score):
if score >= 0.6:
return "积极", "表达正面、肯定的态度,情绪偏向愉悦、满意。"
elif score <= 0.4:
return "消极", "体现负面、否定的态度,情绪可能是沮丧、愤怒等。"
else:
return "中性", "情感倾向不明显,态度较为客观、平和。"
对于每条社交媒体帖子,先调用数据预处理模块得到标准化文本,再创建 SnowNLP
对象,通过其 sentiments
属性获取 0 到 1 之间的情感得分,量化文本情感倾向。然后依据 get_sentiment_category_info
函数,按得分阈值划分情感类别:大于等于 0.6 为“积极”,对应描述解释该情感内涵;小于等于 0.4 为“消极”,同样有相应描述;介于两者间为“中性”。最终将原始文本、分词后文本、情感得分、情感类别及描述等信息整合存储,实现从单纯数值到语义丰富的情感分类转变,提升结果实用性。
在社交媒体舆情监测里,了解关键词热度可把握舆论焦点,由 keyword_heat_analysis
函数完成,代码如下:
def keyword_heat_analysis(posts, keywords):
keyword_counts = {keyword: 0 for keyword in keywords}
for post in posts:
for keyword in keywords:
keyword_counts[keyword] += post.count(keyword)
return keyword_counts
该函数接收社交媒体文本集合与关键词列表,遍历每条文本,针对列表中每个关键词,用字符串的 count
方法统计其在文本中的出现频次,将结果存于以关键词为键、出现次数为值的字典。如关注“政策”“服务”“天气”,若文本“新政策实施后服务质量提升,天气也不错”,“政策”“服务”“天气”对应计数分别加 1,最终返回字典呈现关键词热度分布,助研究人员定位舆论热点。
舆情趋势分析旨在动态捕捉舆情演变态势,通过 sentiment_trend_analysis
函数实现:
def sentiment_trend_analysis(posts, num_stages=3):
stage_size = len(posts) // num_stages
sentiment_trends = []
for i in range(num_stages):
start = i * stage_size
end = (i + 1) * stage_size if i < num_stages - 1 else len(posts)
stage_posts = posts[start:end]
stage_sentiment_scores = [
multi_dim_sentiment_analysis([post])[0]['情感得分'] for post in stage_posts
]
return sentiment_trends
函数以社交媒体帖子集合为输入,默认将文本按三等分(可调整)划分阶段模拟不同时段舆情。在各阶段,调用 multi_dim_sentiment_analysis
函数获取文本情感得分,计算平均值作为阶段舆情平均情感倾向指标。如阶段内文本情感得分高,表明舆情积极;反之则消极。通过连续观察多阶段平均情感得分,展现舆情起伏变化,为预测走向提供线索。
为呈现舆情分析全貌并评估模型性能,设有 final_sentiment_summary
与 evaluate_model
函数。
def final_sentiment_summary(analysis_results):
sentiment_count = {"积极": 0, "中性": 0, "消极": 0}
total = len(analysis_results)
for result in analysis_results:
sentiment_count[result["情感类别"]] += 1
for sentiment, count in sentiment_count.items():
percentage = count / total * 100
print(f"{sentiment}情感文本数量:{count}")
print(f"{sentiment}情感占比:{percentage:.2f}%")
def evaluate_model(true_labels, predicted_labels):
accuracy = accuracy_score(true_labels, predicted_labels)
report = classification_report(true_labels, predicted_labels)
print(f"模型准确率: {accuracy}")
print("分类报告:")
print(report)
final_sentiment_summary
函数遍历 multi_dim_sentiment_analysis
生成结果,按情感类别统计数量并结合总数算占比,直观呈现舆情整体情感格局,助决策者把握公众态度。evaluate_model
函数在有真实标签(需人工标注且与预测标签长度匹配)时,用 sklearn
库工具算模型准确率、生成分类报告,含精确率、召回率、F1 值等,评估模型性能,为优化提供依据。
综上,各模块紧密协作,构建完整高效社交媒体舆情监测系统,满足精准把控舆情需求。
import pandas as pd
from sklearn.metrics import accuracy_score, classification_report
import re
from snownlp import SnowNLP
import jieba
import string
# 更复杂的数据预处理
def advanced_preprocess_text(text):
# 去除标点符号
translator = str.maketrans('', '', string.punctuation)
text = text.translate(translator)
# 去除特殊字符
text = re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9]', ' ', text)
# 分词
words = jieba.lcut(text)
# 去除停用词
stopwords = set()
try:
with open('stopwords.txt', 'r', encoding='utf-8') as f:
for line in f:
stopwords.add(line.strip())
except FileNotFoundError:
pass
filtered_words = [word for word in words if word not in stopwords]
return ' '.join(filtered_words)
# 根据情感得分返回情感类别和描述信息
def get_sentiment_category_info(score):
if score >= 0.6:
return "积极", "表达正面、肯定的态度,情绪偏向愉悦、满意。"
elif score <= 0.4:
return "消极", "体现负面、否定的态度,情绪可能是沮丧、愤怒等。"
else:
return "中性", "情感倾向不明显,态度较为客观、平和。"
# 进行多维度情感分析
# 评估模型
# 存储结果到 CSV 文件
def save_results_to_csv(results, file_path):
df = pd.DataFrame(results)
try:
df.to_csv(file_path, index=False)
print(f"结果已保存到 {file_path}")
except Exception as e:
print(f"保存结果到 CSV 文件时出错: {e}")
# 关键词热度分析
def keyword_heat_analysis(posts, keywords):
keyword_counts = {keyword: 0 for keyword in keywords}
for post in posts:
for keyword in keywords:
keyword_counts[keyword] += post.count(keyword)
return keyword_counts
# 舆情趋势分析(简单示例,按文本顺序划分阶段统计情感均值)
def sentiment_trend_analysis(posts, num_stages=3):
stage_size = len(posts) // num_stages
sentiment_trends = []
for i in range(num_stages):
start = i * stage_size
end = (i + 1) * stage_size if i < num_stages - 1 else len(posts)
stage_posts = posts[start:end]
stage_sentiment_scores = [
multi_dim_sentiment_analysis([post])[0]['情感得分'] for post in stage_posts
]
average_sentiment = sum(stage_sentiment_scores) / len(stage_sentiment_scores) if stage_sentiment_scores else 0
sentiment_trends.append(average_sentiment)
return sentiment_trends
# 最终舆情结果分析
def final_sentiment_summary(analysis_results):
sentiment_count = {"积极": 0, "中性": 0, "消极": 0}
total = len(analysis_results)
for result in analysis_results:
sentiment_count[result["情感类别"]] += 1
for sentiment, count in sentiment_count.items():
percentage = count / total * 100
print(f"{sentiment}情感文本数量:{count}")
print(f"{sentiment}情感占比:{percentage:.2f}%")
# 主函数
def main():
try:
with open('social_media_reviews.txt', 'r', encoding='utf-8') as file:
sentences = file.readlines()
# 去除每行末尾的换行符
sentences = [sentence.strip() for sentence in sentences]
# 进行多维度情感分析
analysis_results = multi_dim_sentiment_analysis(sentences)
predicted_labels = [result["情感类别"] for result in analysis_results]
# 假设我们有真实的标签用于评估
# 这里需要根据实际情况手动设置真实标签,确保长度和预测标签一致
true_labels = []
if len(true_labels) == len(predicted_labels):
evaluate_model(true_labels, predicted_labels)
else:
print("真实标签和预测标签长度不一致,无法进行评估。")
# 存储结果到 CSV 文件
save_results_to_csv(analysis_results, 'chinese_multi_dim_sentiment_results_snownlp.csv')
# 关键词热度分析
keywords = ["政策", "服务", "天气"]
keyword_heat = keyword_heat_analysis(sentences, keywords)
for keyword, count in keyword_heat.items():
print(f"{keyword} 的热度: {count}")
# 舆情趋势分析
sentiment_trends = sentiment_trend_analysis(sentences)
print("舆情趋势: ", sentiment_trends)
# 最终舆情结果分析
final_sentiment_summary(analysis_results)
# 控制台输出结果
print("\n情感分析结果:")
for result in analysis_results:
print(f"原始文本: {result['原始文本']}")
print(f"分词后文本: {result['分词后文本']}")
print(f"情感得分: {result['情感得分']:.2f}")
print(f"情感类别: {result['情感类别']}")
print(f"情感描述: {result['情感描述']}")
print(f"文本长度: {result['文本长度']}")
print(f"分词数量: {result['分词数量']}")
print("-" * 50)
except FileNotFoundError:
print("未找到文件,请确保 'social_media_reviews.txt' 文件存在。")
if __name__ == "__main__":
main()
完整代码请私信后台(关注后私信)