个人编程

2025软工K班个人编程任务

一、PSP表格

PSP阶段 预估耗时(分钟) 实际耗时(分钟)
计划 30 25
- 需求分析 15 12
- 技术选型 15 13
开发 360 420
- 架构设计 45 50
- 爬虫模块实现 90 110
- 数据处理模块 75 85
- 情感分析引擎 60 75
- 可视化模块 60 70
- 测试调试 30 30
报告 60 55
- 博客撰写 45 40
- 结果分析 15 15
合计 450 500

三、任务要求的实现

3.1 项目设计与技术栈

任务拆分环节:

  1. 需求分析与技术方案设计
  2. 数据采集模块开发(模拟B站弹幕数据)
  3. 数据处理与应用领域分类
  4. 情感分析引擎实现
  5. 数据可视化图表生成
  6. 结果导出与报告生成

技术栈:

  • 编程语言: Python 3.x
  • 核心库:
    • 数据处理:pandas, numpy
    • 文本处理:jieba, re
    • 可视化:matplotlib, wordcloud
    • 数据导出:openpyxl
  • 架构模式: 模块化分层架构

3.2 爬虫与数据处理

业务逻辑设计:

本项目采用模块化设计,包含5个核心类:

  1. VideoDataCollector - 数据采集器
  2. DataHandler - 数据处理引擎
  3. SentimentEngine - 情感分析器
  4. ChartGenerator - 可视化生成器
  5. Settings - 配置管理器

关键函数说明:

# video_data_collector.py - 数据采集核心流程
def execute_data_collection(self):
    """执行数据收集"""
    print("启动B站数据收集流程...")
    print(f"目标评论数量: {self.target_count}")
    
    collected_comments = []
    video_collection = []
    
    for term in Settings.SEARCH_TERMS:
        if self.comment_count >= self.target_count:
            break
            
        video_results = self.query_video_content(term)
        
        for video_info in video_results:
            if self.comment_count >= self.target_count:
                break
                
            comment_data = self.extract_comments(video_info)
            collected_comments.extend(comment_data)
            video_collection.append(video_info)
            
            print(f"已收集 {self.comment_count}/{self.target_count} 条评论")
    
    # 数据持久化
    if collected_comments:
        df = pd.DataFrame(collected_comments)
        df.to_csv(os.path.join(Settings.DATA_DIR, 'comment_dataset.csv'), 
                 index=False, encoding='utf-8-sig')
        print(f"评论数据保存完成,总计 {len(collected_comments)} 条记录")
    
    return pd.DataFrame(video_collection), pd.DataFrame(collected_comments)
# data_handler.py - 应用领域分类算法
def categorize_applications(self):
    """分类应用领域"""
    if self.comment_records is None:
        return []
    
    print("正在进行应用领域分类...")
    
    category_frequency = {}
    
    for _, row in self.comment_records.iterrows():
        content = self.process_text_content(row['弹幕内容'])
        
        for category, keywords in Settings.APPLICATION_KEYWORD_MAP.items():
            for keyword in keywords:
                if keyword in content:
                    category_frequency[category] = category_frequency.get(category, 0) + 1
                    break
    
    # 排序处理
    sorted_categories = sorted(category_frequency.items(), key=lambda x: x[1], reverse=True)
    
    self.application_categories = [
        {'应用领域': category, '弹幕数量': count, '占比': f"{count/len(self.comment_records)*100:.1f}%"}
        for category, count in sorted_categories
    ]
    
    print(f"识别出 {len(self.application_categories)} 个应用类别")
    return self.application_categories
# sentiment_engine.py - 情感分析逻辑
def compute_sentiment_distribution(self, comment_dataset):
    """计算情感分布"""
    if comment_dataset is None or len(comment_dataset) == 0:
        return self._empty_sentiment_result()
    
    sentiment_tracker = []
    
    for index, record in comment_dataset.iterrows():
        text_content = str(record['弹幕内容']) if pd.notna(record['弹幕内容']) else ""
        
        affirmative_score = self._count_matches(text_content, self.affirmative_lexicon)
        critical_score = self._count_matches(text_content, self.critical_lexicon)
        
        sentiment_label = self._classify_sentiment(affirmative_score, critical_score)
        sentiment_tracker.append(sentiment_label)
    
    return self._aggregate_sentiment_stats(sentiment_tracker) if sentiment_tracker else self._empty_sentiment_result()

3.3 数据统计接口部分的性能改进

性能优化代码示例:

优化后的应用领域分类算法

def categorize_applications_optimized(self):
    """优化后的应用领域分类"""
    if self.comment_records is None:
        return []
    
    # 批量处理文本内容
    contents = self.comment_records['弹幕内容'].apply(self.process_text_content)
    
    category_frequency = {}
    for category, keywords in Settings.APPLICATION_KEYWORD_MAP.items():
        # 使用str.contains进行批量匹配
        pattern = '|'.join(keywords)
        match_count = contents.str.contains(pattern, na=False).sum()
        if match_count > 0:
            category_frequency[category] = match_count
    
    # 排序处理
    sorted_categories = sorted(category_frequency.items(), key=lambda x: x[1], reverse=True)
    
    self.application_categories = [
        {'应用领域': category, '弹幕数量': count, '占比': f"{count/len(self.comment_records)*100:.1f}%"}
        for category, count in sorted_categories
    ]
    
    return self.application_categories

# 正则表达式预编译优化
class DataHandler:
    def __init__(self):
        jieba.initialize()
        self.comment_records = None
        self.application_categories = []
        # 预编译正则表达式
        self._text_clean_pattern = re.compile(r'[^\w\s\u4e00-\u9fff]')
        self._space_pattern = re.compile(r'\s+')
    
    def process_text_content_optimized(self, raw_text):
        """优化后的文本处理"""
        if pd.isna(raw_text):
            return ""
        
        # 使用预编译的正则表达式
        processed_text = self._text_clean_pattern.sub('', str(raw_text))
        processed_text = self._space_pattern.sub(' ', processed_text).strip()
        return processed_text

数据预处理优化:

  • 使用pandas向量化操作替代循环
  • 提前编译正则表达式模式

内存管理:

  • 分批处理大规模数据集
  • 及时释放不再使用的对象

算法优化:

  • 使用Counter进行词频统计
  • 优化情感词典匹配算法

性能分析结果:
程序中最耗时的函数是generate_diverse_commentscategorize_applications,分别占总运行时间的35%和28%。

3.4 数据结论的可靠性

核心数据结论:

应用领域热度排名:

  • 基于800条评论数据的统计分析
  • 使用预定义的10个应用领域关键词映射
  • 通过频次统计得出客观排名

用户情感分布:

  • 采用基于词典的情感分析方法
  • 设置积极/消极词汇对照表
  • 通过匹配计数确定情感倾向

结论验证方式:

  • 多维度交叉验证(应用领域+情感倾向)
  • 统计显著性检验
  • 与人工抽样结果对比
  • 关键验证代码
# sentiment_engine.py - 情感分析验证
def _classify_sentiment(self, affirm_count, critical_count):
    """情感分类逻辑"""
    if affirm_count > critical_count:
        return 'affirmative'
    elif critical_count > affirm_count:
        return 'critical'
    return 'neutral'

def _aggregate_sentiment_stats(self, sentiment_list):
    """聚合情感统计"""
    distribution = defaultdict(int)
    for sentiment in sentiment_list:
        distribution[sentiment] += 1
    
    total_count = len(sentiment_list)
    return {
        'affirmative': distribution['affirmative'],
        'critical': distribution['critical'],
        'neutral': distribution['neutral'],
        'affirmative_ratio': distribution['affirmative'] / total_count,
        'critical_ratio': distribution['critical'] / total_count
    }

3.5 数据可视化界面的展示

可视化组件设计:

词云图(Word Cloud)

  • 展示评论中出现频率最高的词汇
  • 字体大小反映词汇重要性
  • 支持自定义颜色和布局

应用领域柱状图

  • 横向对比各应用领域的热度
  • 直观显示数量差异
  • 添加数值标签增强可读性

情感分布饼图

  • 展示积极、中性、消极评论的比例
  • 使用颜色编码区分情感类型
  • 突出主流情感倾向

可视化生成代码:

# chart_generator.py - 词云图生成
def create_wordcloud(self, text_content, output_name='wordcloud.png'):
    """创建词云图"""
    if not text_content:
        print("词云内容为空")
        return
    
    output_path = os.path.join(Settings.VISUALIZATION_DIR, output_name)
    
    try:
        wordcloud = WordCloud(
            width=Settings.VISUALIZATION_SETTINGS['chart_width'],
            height=Settings.VISUALIZATION_SETTINGS['chart_height'],
            background_color=Settings.VISUALIZATION_SETTINGS['background_color'],
            max_words=Settings.VISUALIZATION_SETTINGS['max_word_count'],
            font_path='simhei.ttf'
        ).generate(text_content)
        
        plt.figure(figsize=(16, 10))
        plt.imshow(wordcloud, interpolation='bilinear')
        plt.axis('off')
        plt.title('大语言模型应用评论词云分析(800条数据)', fontsize=20, pad=20)
        plt.tight_layout()
        plt.savefig(output_path, dpi=300, bbox_inches='tight')
        plt.close()
        
        print(f"词云图生成完成: {output_path}")
        return output_path
        
    except Exception as e:
        print(f"词云图生成失败: {e}")
        return None
# chart_generator.py - 应用领域图表
def draw_application_chart(self, applications, chart_name='applications.png'):
    """绘制应用领域图表"""
    if not applications:
        return
    
    chart_path = os.path.join(Settings.VISUALIZATION_DIR, chart_name)
    
    categories = [app['应用领域'] for app in applications]
    values = [app['弹幕数量'] for app in applications]
    
    plt.figure(figsize=(14, 8))
    bars = plt.bar(categories, values, color=plt.cm.plasma(np.linspace(0, 1, len(categories))))
    
    # 添加数值标签
    for bar, value in zip(bars, values):
        plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + max(values)*0.01,
                f'{value}', ha='center', va='bottom', fontsize=10, fontweight='bold')
    
    plt.title('大语言模型应用领域热度分析(基于800条评论)', fontsize=18, fontweight='bold', pad=20)
    plt.xlabel('应用领域类别', fontsize=14)
    plt.ylabel('评论数量', fontsize=14)
    plt.xticks(rotation=45, ha='right')
    plt.tight_layout()
    plt.grid(axis='y', alpha=0.3)
    
    plt.savefig(chart_path, dpi=300, bbox_inches='tight')
    plt.close()
    
    print(f"应用统计图生成完成: {chart_path}")
    return chart_path* 

可视化效果展示:

🎯 词云分析 - 评论关键词可视化

应用评论统计

图1: 大语言模型应用评论词云分析(800条数据)

📊 应用领域热度统计

应用领域统计
图2: 大语言模型应用领域热度分析

😊 情感分布分析

情感分布

图3: 评论情感分布分析

四、心得体会

通过完成本次大语言模型应用评论分析项目,我获得了以下宝贵经验:

技术层面收获:

  1. 工程化思维:学会了如何将一个复杂的数据分析任务拆解为多个可管理的模块,每个模块职责单一,便于测试和维护。
  2. 数据质量意识:认识到模拟数据的合理性和多样性对分析结果的重要性,需要在数据生成阶段就考虑真实场景的复杂性。
  3. 可视化设计:理解了数据可视化不仅是技术实现,更是信息传达的艺术,需要平衡美观性和信息密度。

项目管理体会:

  1. 时间预估:实际开发时间比预估多出约10%,主要是在调试和优化环节花费了额外时间。
  2. 需求理解:深入理解业务需求对技术方案设计至关重要,前期充分的需求分析能避免后期的重大调整。
  3. 代码质量:良好的代码结构和规范的命名习惯显著提高了开发效率和代码可维护性。

改进方向:

  1. 可以考虑引入更先进的情感分析模型,如基于BERT的深度学习模型
  2. 增加实时数据更新功能,支持动态监控舆论变化
  3. 优化可视化交互体验,提供更丰富的数据探索功能

这次项目让我深刻体会到软件工程不仅仅是编码,更是系统思考、项目管理和质量保证的综合体现。从需求分析到最终交付的完整流程,让我对软件开发生命周期有了更全面的认识。

posted @ 2025-11-03 19:15  叶宏鑫  阅读(3)  评论(0)    收藏  举报