计算机Python毕业设计推荐:基于Django的酒店评论文本情感分析系统【源码+文档+调试】

精彩专栏推荐订阅:在 下方专栏👇🏻👇🏻👇🏻👇🏻

💖🔥作者主页计算机毕设木哥🔥 💖

文章目录

一、项目介绍

基于Django的酒店评论文本情感分析系统是一套专门针对酒店行业用户评论进行智能化情感识别与分析的Web应用系统。该系统采用Python作为核心开发语言,结合Django强大的Web框架能力,构建了完整的B/S架构应用。系统前端采用Vue.js配合ElementUI组件库,为用户提供直观友好的操作界面,后端通过Django框架处理业务逻辑,使用MySQL数据库存储酒店信息、用户评论及情感分析结果。系统实现了双重用户角色管理,管理员可以进行用户管理、酒店信息维护、情感分析操作以及酒店信息预测功能,普通用户则可以完成注册登录、浏览酒店信息和发表评论等操作。通过集成自然语言处理技术,系统能够自动识别用户评论中的情感倾向,为酒店经营者提供客观的用户反馈分析,同时为潜在消费者提供更加准确的酒店选择参考。整个系统在PyCharm开发环境中完成,确保了代码的规范性和可维护性。

选题背景

随着互联网技术的快速发展和移动设备的普及,在线酒店预订平台已经成为人们出行住宿的主要选择方式。各类酒店预订网站和应用程序积累了海量的用户评论数据,这些评论文本包含了用户对酒店服务质量、设施环境、地理位置等多个维度的真实反馈。然而,面对数以万计的评论信息,传统的人工阅读和分析方式显然无法满足现代酒店经营管理的需求。酒店管理者需要从大量非结构化的文本评论中快速准确地提取有价值的信息,了解客户满意度趋势,识别服务改进的关键点。与此同时,消费者在选择酒店时也希望能够快速了解其他用户的真实评价倾向,而不是逐一阅读冗长的评论文本。这种供需矛盾催生了对智能化文本情感分析技术的迫切需求,促使相关的自动化分析系统应运而生。

选题意义

本课题的研究具有一定的理论价值和实践意义。在理论层面,通过将自然语言处理技术与Web开发技术相结合,探索了文本情感分析在特定行业场景中的应用模式,为相关领域的技术融合提供了参考案例。在实践应用方面,系统能够帮助酒店经营者更加高效地处理用户反馈信息,通过自动化的情感倾向识别,管理者可以快速掌握客户满意度的整体状况和变化趋势,及时调整经营策略和服务质量。对于消费者而言,系统提供的情感分析结果能够作为选择酒店的辅助参考,提升决策效率和准确性。从技术实现角度来看,本系统整合了Python生态系统中的多个优秀框架和工具,展示了现代Web开发的标准化流程和最佳实践,对于学习和掌握相关技术栈具有一定的教学和示范价值。虽然作为毕业设计项目,系统规模和复杂度相对有限,但其完整的功能设计和规范的技术架构仍然体现了软件工程的基本原理和方法。

二、开发环境

  • 大数据技术:Hadoop、Spark、Hive
  • 开发技术:Python、Django框架、Vue、Echarts
  • 软件工具:Pycharm、DataGrip、Anaconda
  • 可视化 工具 Echarts

三、视频展示

计算机Python毕业设计推荐:基于Django的酒店评论文本情感分析系统【源码+文档+调试】

四、项目展示

登录模块:

首页模块:




管理模块:






五、代码展示

bash 复制代码
from pyspark.sql import SparkSession
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.db import connection
from .models import Hotel, Comment, SentimentResult
import json
import jieba
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import re

spark = SparkSession.builder.appName("HotelSentimentAnalysis").config("spark.sql.adaptive.enabled", "true").config("spark.sql.adaptive.coalescePartitions.enabled", "true").getOrCreate()

def hotel_sentiment_analysis(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        hotel_id = data.get('hotel_id')
        try:
            hotel = Hotel.objects.get(id=hotel_id)
            comments = Comment.objects.filter(hotel=hotel)
            comment_texts = [comment.content for comment in comments]
            positive_words = ['好', '棒', '优秀', '满意', '推荐', '舒适', '干净', '方便', '温馨', '贴心']
            negative_words = ['差', '糟糕', '失望', '不满', '脏', '吵', '贵', '远', '冷', '热']
            sentiment_scores = []
            for text in comment_texts:
                cleaned_text = re.sub(r'[^\u4e00-\u9fff]', '', text)
                words = list(jieba.cut(cleaned_text))
                positive_count = sum(1 for word in words if word in positive_words)
                negative_count = sum(1 for word in words if word in negative_words)
                if positive_count > negative_count:
                    sentiment = 'positive'
                    score = (positive_count - negative_count) / len(words) if words else 0
                elif negative_count > positive_count:
                    sentiment = 'negative'
                    score = (negative_count - positive_count) / len(words) if words else 0
                else:
                    sentiment = 'neutral'
                    score = 0
                sentiment_scores.append({'sentiment': sentiment, 'score': score})
            positive_rate = len([s for s in sentiment_scores if s['sentiment'] == 'positive']) / len(sentiment_scores) if sentiment_scores else 0
            negative_rate = len([s for s in sentiment_scores if s['sentiment'] == 'negative']) / len(sentiment_scores) if sentiment_scores else 0
            neutral_rate = len([s for s in sentiment_scores if s['sentiment'] == 'neutral']) / len(sentiment_scores) if sentiment_scores else 0
            overall_sentiment = 'positive' if positive_rate > negative_rate else ('negative' if negative_rate > positive_rate else 'neutral')
            avg_score = np.mean([s['score'] for s in sentiment_scores]) if sentiment_scores else 0
            SentimentResult.objects.create(
                hotel=hotel,
                positive_rate=positive_rate,
                negative_rate=negative_rate,
                neutral_rate=neutral_rate,
                overall_sentiment=overall_sentiment,
                average_score=avg_score
            )
            return JsonResponse({
                'status': 'success',
                'data': {
                    'hotel_name': hotel.name,
                    'positive_rate': round(positive_rate * 100, 2),
                    'negative_rate': round(negative_rate * 100, 2),
                    'neutral_rate': round(neutral_rate * 100, 2),
                    'overall_sentiment': overall_sentiment,
                    'average_score': round(avg_score, 3),
                    'total_comments': len(comment_texts)
                }
            })
        except Hotel.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '酒店不存在'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})

def hotel_info_prediction(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        hotel_id = data.get('hotel_id')
        try:
            hotel = Hotel.objects.get(id=hotel_id)
            sentiment_results = SentimentResult.objects.filter(hotel=hotel).order_by('-created_at')[:30]
            if len(sentiment_results) < 10:
                return JsonResponse({'status': 'error', 'message': '历史数据不足,无法进行预测'})
            historical_scores = [result.average_score for result in sentiment_results]
            historical_positive_rates = [result.positive_rate for result in sentiment_results]
            recent_trend = np.mean(historical_scores[-5:]) - np.mean(historical_scores[-10:-5]) if len(historical_scores) >= 10 else 0
            score_variance = np.var(historical_scores)
            positive_trend = np.mean(historical_positive_rates[-5:]) - np.mean(historical_positive_rates[-10:-5]) if len(historical_positive_rates) >= 10 else 0
            predicted_score = historical_scores[-1] + (recent_trend * 0.3)
            predicted_positive_rate = historical_positive_rates[-1] + (positive_trend * 0.25)
            stability_factor = 1 / (1 + score_variance) if score_variance > 0 else 1
            confidence_level = min(0.95, 0.6 + stability_factor * 0.35)
            if predicted_score > 0.6:
                prediction_level = '优秀'
                recommendation = '该酒店预计将保持较高的客户满意度'
            elif predicted_score > 0.3:
                prediction_level = '良好'
                recommendation = '该酒店预计将维持中等偏上的服务水平'
            elif predicted_score > 0:
                prediction_level = '一般'
                recommendation = '该酒店预计需要关注服务质量提升'
            else:
                prediction_level = '需改进'
                recommendation = '该酒店预计需要重点改善客户体验'
            return JsonResponse({
                'status': 'success',
                'data': {
                    'hotel_name': hotel.name,
                    'predicted_score': round(predicted_score, 3),
                    'predicted_positive_rate': round(predicted_positive_rate * 100, 2),
                    'prediction_level': prediction_level,
                    'confidence_level': round(confidence_level * 100, 2),
                    'recommendation': recommendation,
                    'trend_direction': '上升' if recent_trend > 0 else ('下降' if recent_trend < 0 else '稳定'),
                    'data_points': len(historical_scores)
                }
            })
        except Hotel.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '酒店不存在'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})

@csrf_exempt
def user_management(request):
    if request.method == 'GET':
        try:
            users = User.objects.all().exclude(is_superuser=True)
            user_list = []
            for user in users:
                comment_count = Comment.objects.filter(user=user).count()
                last_login_time = user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else '从未登录'
                user_status = '活跃' if comment_count > 5 else ('一般' if comment_count > 0 else '不活跃')
                user_info = {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'date_joined': user.date_joined.strftime('%Y-%m-%d'),
                    'last_login': last_login_time,
                    'is_active': user.is_active,
                    'comment_count': comment_count,
                    'user_status': user_status
                }
                user_list.append(user_info)
            user_list.sort(key=lambda x: x['comment_count'], reverse=True)
            active_users = len([u for u in user_list if u['is_active']])
            total_comments = sum([u['comment_count'] for u in user_list])
            avg_comments_per_user = round(total_comments / len(user_list), 2) if user_list else 0
            return JsonResponse({
                'status': 'success',
                'data': {
                    'users': user_list,
                    'statistics': {
                        'total_users': len(user_list),
                        'active_users': active_users,
                        'total_comments': total_comments,
                        'avg_comments_per_user': avg_comments_per_user
                    }
                }
            })
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})
    elif request.method == 'POST':
        data = json.loads(request.body)
        action = data.get('action')
        user_id = data.get('user_id')
        try:
            if action == 'activate':
                user = User.objects.get(id=user_id)
                user.is_active = True
                user.save()
                return JsonResponse({'status': 'success', 'message': '用户已激活'})
            elif action == 'deactivate':
                user = User.objects.get(id=user_id)
                user.is_active = False
                user.save()
                return JsonResponse({'status': 'success', 'message': '用户已禁用'})
            elif action == 'delete':
                user = User.objects.get(id=user_id)
                Comment.objects.filter(user=user).delete()
                user.delete()
                return JsonResponse({'status': 'success', 'message': '用户已删除'})
            else:
                return JsonResponse({'status': 'error', 'message': '无效的操作类型'})
        except User.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': '用户不存在'})
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)})

六、项目文档展示

七、总结

基于Python的酒店评论文本情感分析系统作为一个完整的毕业设计项目,成功地将自然语言处理技术与现代Web开发技术进行了有机结合。该系统采用Django框架作为后端核心,配合Vue.js和ElementUI构建用户友好的前端界面,通过MySQL数据库实现数据的持久化存储,形成了一套技术架构清晰、功能相对完整的B/S结构应用。系统实现的酒店评论情感分析功能能够自动识别用户评论中的情感倾向,为酒店管理者提供客观的用户反馈分析,同时通过用户管理和酒店信息预测等功能,构建了相对完善的业务流程。虽然作为本科毕业设计,系统在算法复杂度和业务深度方面还有提升空间,但其展现的技术整合能力和问题解决思路体现了较好的工程实践水平。项目的完成过程涉及了前后端开发、数据库设计、自然语言处理等多个技术领域,对于提升综合开发能力和加深对软件工程流程的理解具有重要作用。通过这个项目的实施,不仅掌握了Python Web开发的核心技术栈,也初步了解了文本挖掘和情感分析的基本原理,为今后在相关技术领域的深入学习和职业发展奠定了良好基础。

大家可以帮忙点赞、收藏、关注、评论啦👇🏻👇🏻👇🏻

💖🔥作者主页计算机毕设木哥🔥 💖

相关推荐
BYSJMG4 小时前
基于Python毕业设计推荐:基于Django的全国降水分析可视化系统
hadoop·python·django·vue·毕业设计·课程设计·毕设
飞天小蜈蚣5 小时前
python - ( js )object对象、json对象、字符串对象的相关方法、数组对象的相关方法、BOM对象、BOM模型中 Navigator 对象
javascript·python·json
一枝小雨5 小时前
【C++】编写通用模板代码的重要技巧:T()
开发语言·c++·笔记·学习笔记
XueminXu5 小时前
Spark引擎中RDD的性质
spark·cache·map·rdd·flatmap·弹性分布式数据集·collect
0wioiw07 小时前
C#基础(⑥动态链接库DLL)
开发语言·c#
04Koi.7 小时前
面经分享--华为Java一面
java·开发语言
云手机掌柜7 小时前
Twitter舆情裂变链:指纹云手机跨账号协同机制提升互动率200%
python·网络安全·智能手机·矩阵·虚幻·内容运营·twitter
2401_897930067 小时前
python 创建websocket教程
开发语言·python·websocket
AI Echoes8 小时前
LangGraph 重要注意事项和常见问题
人工智能·python·langchain·agent