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

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)

相关推荐
scx_link5 分钟前
Word2Vec词嵌入技术和动态词嵌入技术
人工智能·自然语言处理·word2vec
云梦谭7 分钟前
Cursor 编辑器:面向 AI 编程的新一代 IDE
ide·人工智能·编辑器
IT_陈寒17 分钟前
Redis性能提升50%的7个关键优化策略,90%开发者都不知道第5点!
前端·人工智能·后端
乐迪信息23 分钟前
乐迪信息:AI摄像机在智慧煤矿人员安全与行为识别中的技术应用
大数据·人工智能·算法·安全·视觉检测
AI人工智能+23 分钟前
炫光活体检测技术:通过光学技术实现高效、安全的身份验证,有效防御多种伪造手段。
人工智能·深度学习·人脸识别·活体检测
咔咔一顿操作33 分钟前
第七章 Cesium 3D 粒子烟花效果案例解析:从原理到完整代码
人工智能·3d·信息可视化·cesium
微三云-轩1 小时前
区块链:重构企业数字化的信任核心与创新动力
人工智能·小程序·区块链·生活·我店
君名余曰正则1 小时前
机器学习04——决策树(信息增益、信息增益率、ID3、C4.5、CART、剪枝、连续值缺失值处理)
人工智能·决策树·机器学习
中电金信1 小时前
中电金信:AI重构测试体系·智能化时代的软件工程新范式
人工智能·重构·软件工程
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc