清洗文本高频词、情感分析、情感分类、主题建模挖掘主题

import pandas as pd

import re

import nltk

from nltk import FreqDist

from nltk.sentiment.vader import SentimentIntensityAnalyzer

from nltk.tokenize import word_tokenize

import spacy

from spacy.lang.en.stop_words import STOP_WORDS

from gensim.corpora import Dictionary

from gensim.models import LdaModel

下载NLTK的停用词、情感分析和词性标注所需的资源

nltk.download('stopwords')

nltk.download('punkt')

nltk.download('vader_lexicon')

加载SpaCy的英文NLP模型

nlp = spacy.load("en_core_web_sm")

读取Excel文件

df = pd.read_excel('nltk分词处理结果第二次.xlsx')

定义文本清洗函数

def clean_text(text):

去除HTML标签

cleaned_text = re.sub(r'<.*?>', '', text)

去除多余空格和换行符

cleaned_text = re.sub(r'\s+', ' ', cleaned_text)

转换为小写

cleaned_text = cleaned_text.lower()

return cleaned_text

清洗文本数据

df['cleaned_content'] = df['content'].apply(clean_text)

词频分析

words = []

for text in df['cleaned_content']:

words += word_tokenize(text)

freq_dist = FreqDist(words)

print("词频分析结果:", freq_dist.most_common(10))

情感分析

sia = SentimentIntensityAnalyzer()

df['sentiment_score'] = df['cleaned_content'].apply(lambda x: sia.polarity_scores(x)['compound'])

print("情感分析结果:", df['sentiment_score'])

定义阈值

positive_threshold = 0.5

negative_threshold = -0.5

根据情感分数进行分类

def classify_sentiment(score):

if score > positive_threshold:

return '积极'

elif score < negative_threshold:

return '消极'

else:

return '中性'

应用分类函数,创建新的列 'sentiment_category'

df['sentiment_category'] = df['sentiment_score'].apply(classify_sentiment)

输出带有情感分类的数据

print(df[['cleaned_content', 'sentiment_score', 'sentiment_category']])

主题建模

tokens = [[token.text.lower() for token in nlp(text) if token.is_alpha and token.text.lower() not in STOP_WORDS] for text in df['cleaned_content']]

dictionary = Dictionary(tokens)

corpus = [dictionary.doc2bow(text) for text in tokens]

lda_model = LdaModel(corpus, num_topics=5, id2word=dictionary, passes=15)

topics = lda_model.print_topics(num_words=5)

print("主题建模结果:")

for topic in topics:

print(topic)

相关推荐
Stara051123 分钟前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
YuSun_WK26 分钟前
目标跟踪相关综述文章
人工智能·计算机视觉·目标跟踪
一切皆有可能!!30 分钟前
RAG数据处理:PDF/HTML
人工智能·语言模型
kyle~31 分钟前
深度学习---知识蒸馏(Knowledge Distillation, KD)
人工智能·深度学习
那雨倾城1 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
whoarethenext1 小时前
c/c++的opencv的图像预处理讲解
人工智能·opencv·计算机视觉·预处理
金融小师妹2 小时前
应用BERT-GCN跨模态情绪分析:贸易缓和与金价波动的AI归因
大数据·人工智能·算法
武子康2 小时前
大语言模型 10 - 从0开始训练GPT 0.25B参数量 补充知识之模型架构 MoE、ReLU、FFN、MixFFN
大数据·人工智能·gpt·ai·语言模型·自然语言处理
广州智造2 小时前
OptiStruct实例:3D实体转子分析
数据库·人工智能·算法·机器学习·数学建模·3d·性能优化
jndingxin4 小时前
OpenCV CUDA模块中矩阵操作------降维操作
人工智能·opencv