基于Python的中文文本处理与分析程序:功能详解与实战应用

在当今信息爆炸的时代,文本数据的处理与分析成为了数据科学领域的重要课题。特别是对于中文文本,由于其独特的语言特性和复杂的语法结构,处理起来更具挑战性。为了解决这个问题,我们开发了一款基于Python的中文文本处理与分析程序。该程序集成了文件操作、基础分析、高级分析、可视化以及自然语言处理(NLP)等多种功能,旨在为用户提供一个全面、易用的文本处理工具。本文将对该程序的主要功能进行详细解析,并通过实战应用展示其强大的处理能力。

一、程序概述

该程序是一个集文本处理、分析、可视化及NLP任务于一体的综合工具。它利用Python的多个强大库,如jieba、matplotlib、networkx、pandas和scikit-learn等,实现了文本的分词、词性标注、命名实体识别、关键词提取、词频统计、字符数统计、句子数统计、词云图生成、词频柱状图生成、词语共现网络生成以及文本分类、情感分析和文本摘要等功能。程序提供了一个简洁直观的图形用户界面(GUI),使得用户无需深入了解底层实现即可轻松完成文本处理与分析任务。

二、主要功能解析

2.1 文件操作

程序提供了文件操作功能,允许用户选择输入文件和输出文件,以及停用词文件。用户可以通过点击“浏览”按钮来选择文件,程序会自动读取文件内容并在日志区域显示相关信息。对于停用词文件,程序会读取文件中的词语并将其作为停用词,用于后续的分词和文本处理任务。

2.2 基础分析

基础分析功能包括词频统计、字符数统计和句子数统计。用户可以通过勾选相应的复选框来选择需要执行的分析任务。

  • 词频统计:程序会对文本进行分词,并统计每个词语的出现频率。用户可以选择显示前N个高频词语(默认为前10个)。
  • 字符数统计:程序会统计文本的总字符数,并在日志区域显示结果。
  • 句子数统计:程序会根据标点符号将文本拆分成句子,并统计句子的总数。

2.3 高级分析

高级分析功能包括词性标注、命名实体识别和关键词提取。这些功能依赖于jieba库的词性标注和关键词提取模块。

  • 词性标注:程序会对文本进行分词和词性标注,并显示前N个词语及其词性(默认为前20个)。
  • 命名实体识别:程序会识别文本中的命名实体(如人名、地名、机构名等),并统计每个实体的出现频率。用户可以选择显示前N个高频实体(默认为前10个)。
  • 关键词提取:程序会提取文本中的关键词,并显示前N个关键词(默认为前10个)。

2.4 可视化

可视化功能包括词云图生成、词频柱状图生成和词语共现网络生成。这些功能依赖于matplotlib和networkx库。

  • 词云图:程序会根据词频生成词云图,直观展示文本中的高频词语。
  • 词频柱状图:程序会生成词频柱状图,展示前N个高频词语及其频率(默认为前20个)。
  • 词语共现网络:程序会根据词语的共现关系生成共现网络图,展示词语之间的关联程度。

2.5 NLP任务

NLP任务功能包括文本分类、情感分析和文本摘要。这些功能依赖于scikit-learn库和jieba库的关键词提取模块。

  • 文本分类:程序会根据文本内容将其分类到预定义的类别中。这里我们使用了一个简单的基于关键词的分类方法作为示例。
  • 情感分析:程序会分析文本的情感倾向(正面、负面或中性)。这里我们使用了一个简单的基于词典的情感分析方法作为示例。
  • 文本摘要:程序会生成文本的摘要,提取出文本中的关键信息。这里我们使用了TF-IDF算法来计算句子的重要性,并选择重要性最高的N个句子作为摘要(默认为前3个)。

三、实战应用

3.1 文本预处理

首先,我们需要对文本进行预处理,包括去除标点符号、停用词等。这些步骤对于后续的文本分析和可视化至关重要。

# 选择输入文件和停用词文件
analyzer.select_input_file()
analyzer.select_stopwords_file()
# 处理文件
analyzer.process_file()

3.2 基础分析

接下来,我们可以执行一些基础分析任务,如词频统计、字符数统计和句子数统计。

# 执行基础分析
analyzer.word_frequency_analysis()
analyzer.character_count_analysis()
analyzer.sentence_count_analysis()

3.3 高级分析

在基础分析的基础上,我们可以进一步执行高级分析任务,如词性标注、命名实体识别和关键词提取。

# 执行高级分析
analyzer.pos_tagging_analysis()
analyzer.named_entity_recognition()
analyzer.keyword_extraction_analysis()

3.4 可视化

为了更直观地展示文本分析结果,我们可以生成词云图、词频柱状图和词语共现网络。

# 执行可视化
analyzer.generate_word_cloud()
analyzer.generate_word_freq_chart()
analyzer.generate_word_cooccurrence_network()

3.5 NLP任务

最后,我们可以执行一些NLP任务,如文本分类、情感分析和文本摘要。

# 执行NLP任务
analyzer.text_classification()
analyzer.sentiment_analysis()
analyzer.text_summarization()

四、技术实现

4.1 GUI构建

程序利用tkinter库构建GUI界面。tkinter是Python的标准GUI库,提供了丰富的控件和布局管理器,使得构建复杂的GUI界面变得简单直观。

4.2 文本处理

程序利用jieba库进行文本处理。jieba是一个中文文本分词工具,支持三种分词模式:精确模式、全模式和搜索引擎模式。此外,jieba还提供了词性标注、命名实体识别和关键词提取等功能。

4.3 数据可视化

程序利用matplotlib和networkx库进行数据可视化。matplotlib是Python的一个绘图库,提供了丰富的绘图函数和接口,使得绘制各种静态、动态和交互式的图表变得简单快捷。networkx是一个用于创建、操作和研究复杂网络的Python包,支持创建、绘制和分析各种类型的网络图。

4.4 NLP任务

程序利用scikit-learn库执行NLP任务。scikit-learn是一个开源的机器学习库,提供了大量的算法和工具,用于数据挖掘和数据分析。在NLP任务中,我们主要使用了TF-IDF算法和简单的分类、情感分析方法。

五、总结与展望

本文详细解析了一款基于Python的中文文本处理与分析程序的主要功能及其实现方式。该程序提供了一个简洁直观的GUI界面,使得用户无需深入了解底层实现即可轻松完成文本处理与分析任务。通过集成文件操作、基础分析、高级分析、可视化以及NLP任务等多种功能,该程序能够满足用户在文本处理与分析方面的多种需求。

未来,我们将继续优化和完善该程序,增加更多的文本处理和分析功能,提高程序的性能和稳定性。同时,我们也将探索更多的NLP任务和应用场景,为用户提供更加全面和强大的文本处理与分析工具。希望本文能够为读者提供有益的参考和借鉴,推动中文文本处理与分析技术的发展和应用。

展示如下:

文本摘要仍要改进,欢迎二创!

目前完整代码:

# -*- coding: utf-8 -*-
import sys
import os
import jieba
import jieba.posseg as pseg
import jieba.analyse
import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from collections import Counter
import re
import networkx as nx
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import numpy as np
import string

class ChineseTextAnalyzer:
    def __init__(self):
        self.window = tk.Tk()
        self.window.title("中文文本分析程序")
        self.window.geometry("800x600")

        self.notebook = ttk.Notebook(self.window)
        self.notebook.pack(fill=tk.BOTH, expand=True)

        self.input_file = ""
        self.output_file = ""
        self.text_content = ""
        self.stopwords = set()
        self.punctuation = set(string.punctuation + ',。!?、;:""''()【】《》')

        self.create_file_tab()
        self.create_basic_analysis_tab()
        self.create_advanced_analysis_tab()
        self.create_visualization_tab()
        self.create_nlp_tab()

    def create_file_tab(self):
        file_tab = ttk.Frame(self.notebook)
        self.notebook.add(file_tab, text="文件操作")

        input_frame = ttk.LabelFrame(file_tab, text="输入文件")
        input_frame.pack(fill=tk.X, padx=5, pady=5)

        self.input_entry = ttk.Entry(input_frame, width=50)
        self.input_entry.pack(side=tk.LEFT, padx=5, pady=5)

        input_button = ttk.Button(input_frame, text="浏览", command=self.select_input_file)
        input_button.pack(side=tk.LEFT, padx=5, pady=5)

        stopwords_frame = ttk.LabelFrame(file_tab, text="停用词文件")
        stopwords_frame.pack(fill=tk.X, padx=5, pady=5)

        self.stopwords_entry = ttk.Entry(stopwords_frame, width=50)
        self.stopwords_entry.pack(side=tk.LEFT, padx=5, pady=5)

        stopwords_button = ttk.Button(stopwords_frame, text="浏览", command=self.select_stopwords_file)
        stopwords_button.pack(side=tk.LEFT, padx=5, pady=5)

        process_button = ttk.Button(file_tab, text="处理文件", command=self.process_file)
        process_button.pack(pady=10)

        self.file_log = tk.Text(file_tab, height=10)
        self.file_log.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def create_basic_analysis_tab(self):
        basic_tab = ttk.Frame(self.notebook)
        self.notebook.add(basic_tab, text="基础分析")

        options_frame = ttk.LabelFrame(basic_tab, text="分析选项")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.word_freq_var = tk.BooleanVar()
        word_freq_check = ttk.Checkbutton(options_frame, text="词频统计", variable=self.word_freq_var)
        word_freq_check.pack(anchor=tk.W)

        self.char_count_var = tk.BooleanVar()
        char_count_check = ttk.Checkbutton(options_frame, text="字符数统计", variable=self.char_count_var)
        char_count_check.pack(anchor=tk.W)

        self.sentence_count_var = tk.BooleanVar()
        sentence_count_check = ttk.Checkbutton(options_frame, text="句子数统计", variable=self.sentence_count_var)
        sentence_count_check.pack(anchor=tk.W)

        analyze_button = ttk.Button(basic_tab, text="开始分析", command=self.perform_basic_analysis)
        analyze_button.pack(pady=10)

        self.basic_log = tk.Text(basic_tab, height=10)
        self.basic_log.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def create_advanced_analysis_tab(self):
        advanced_tab = ttk.Frame(self.notebook)
        self.notebook.add(advanced_tab, text="高级分析")

        options_frame = ttk.LabelFrame(advanced_tab, text="分析选项")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.pos_tagging_var = tk.BooleanVar()
        pos_tagging_check = ttk.Checkbutton(options_frame, text="词性标注", variable=self.pos_tagging_var)
        pos_tagging_check.pack(anchor=tk.W)

        self.named_entity_var = tk.BooleanVar()
        named_entity_check = ttk.Checkbutton(options_frame, text="命名实体识别", variable=self.named_entity_var)
        named_entity_check.pack(anchor=tk.W)

        self.keyword_extraction_var = tk.BooleanVar()
        keyword_extraction_check = ttk.Checkbutton(options_frame, text="关键词提取", variable=self.keyword_extraction_var)
        keyword_extraction_check.pack(anchor=tk.W)

        analyze_button = ttk.Button(advanced_tab, text="开始分析", command=self.perform_advanced_analysis)
        analyze_button.pack(pady=10)

        self.advanced_log = tk.Text(advanced_tab, height=10)
        self.advanced_log.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def create_visualization_tab(self):
        visualization_tab = ttk.Frame(self.notebook)
        self.notebook.add(visualization_tab, text="可视化")

        options_frame = ttk.LabelFrame(visualization_tab, text="可视化选项")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.word_cloud_var = tk.BooleanVar()
        word_cloud_check = ttk.Checkbutton(options_frame, text="词云图", variable=self.word_cloud_var)
        word_cloud_check.pack(anchor=tk.W)

        self.word_freq_chart_var = tk.BooleanVar()
        word_freq_chart_check = ttk.Checkbutton(options_frame, text="词频柱状图", variable=self.word_freq_chart_var)
        word_freq_chart_check.pack(anchor=tk.W)

        self.word_cooccurrence_var = tk.BooleanVar()
        word_cooccurrence_check = ttk.Checkbutton(options_frame, text="词语共现网络", variable=self.word_cooccurrence_var)
        word_cooccurrence_check.pack(anchor=tk.W)

        visualize_button = ttk.Button(visualization_tab, text="生成可视化", command=self.perform_visualization)
        visualize_button.pack(pady=10)

        self.visualization_log = tk.Text(visualization_tab, height=10)
        self.visualization_log.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def create_nlp_tab(self):
        nlp_tab = ttk.Frame(self.notebook)
        self.notebook.add(nlp_tab, text="NLP任务")

        options_frame = ttk.LabelFrame(nlp_tab, text="NLP选项")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.text_classification_var = tk.BooleanVar()
        text_classification_check = ttk.Checkbutton(options_frame, text="文本分类", variable=self.text_classification_var)
        text_classification_check.pack(anchor=tk.W)

        self.sentiment_analysis_var = tk.BooleanVar()
        sentiment_analysis_check = ttk.Checkbutton(options_frame, text="情感分析", variable=self.sentiment_analysis_var)
        sentiment_analysis_check.pack(anchor=tk.W)

        self.text_summarization_var = tk.BooleanVar()
        text_summarization_check = ttk.Checkbutton(options_frame, text="文本摘要", variable=self.text_summarization_var)
        text_summarization_check.pack(anchor=tk.W)

        nlp_button = ttk.Button(nlp_tab, text="执行NLP任务", command=self.perform_nlp_tasks)
        nlp_button.pack(pady=10)

        self.nlp_log = tk.Text(nlp_tab, height=10)
        self.nlp_log.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)

    def select_input_file(self):
        """选择输入文件"""
        self.input_file = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
        self.input_entry.delete(0, tk.END)
        self.input_entry.insert(0, self.input_file)
        self.file_log.insert(tk.END, f"已选择输入文件: {self.input_file}\n")

    def select_output_file(self):
        """选择输出文件"""
        self.output_file = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
        self.output_entry.delete(0, tk.END)
        self.output_entry.insert(0, self.output_file)
        self.file_log.insert(tk.END, f"已选择输出文件: {self.output_file}\n")

    def select_stopwords_file(self):
        """选择停用词文件"""
        stopwords_file = filedialog.askopenfilename(filetypes=[("Text files", "*.txt")])
        self.stopwords_entry.delete(0, tk.END)
        self.stopwords_entry.insert(0, stopwords_file)
        self.file_log.insert(tk.END, f"已选择停用词文件: {stopwords_file}\n")

        # 读取停用词
        try:
            with open(stopwords_file, 'r', encoding='utf-8') as f:
                self.stopwords = set(line.strip() for line in f)
            self.file_log.insert(tk.END, f"成功读取 {len(self.stopwords)} 个停用词\n")
        except Exception as e:
            self.file_log.insert(tk.END, f"读取停用词文件失败: {str(e)}\n")

    def process_file(self):
        """处理文件"""
        if not self.input_file:
            messagebox.showerror("错误", "请选择输入文件")
            return

        try:
            with open(self.input_file, 'r', encoding='utf-8') as f:
                self.text_content = f.read()
            self.file_log.insert(tk.END, f"文件读取成功,共 {len(self.text_content)} 个字符\n")

            # 去除标点符号
            self.text_content = ''.join(char for char in self.text_content if char not in self.punctuation)

            # 如果有停用词,进行分词并去除停用词
            if self.stopwords:
                words = jieba.lcut(self.text_content)
                filtered_words = [word for word in words if word not in self.stopwords]
                self.text_content = ' '.join(filtered_words)
                self.file_log.insert(tk.END, f"已去除停用词和标点符号,处理后共 {len(filtered_words)} 个词\n")
            else:
                self.file_log.insert(tk.END, "已去除标点符号\n")
        except Exception as e:
            self.file_log.insert(tk.END, f"文件读取失败: {str(e)}\n")

    def perform_basic_analysis(self):
        """执行基础分析"""
        if not self.text_content:
            messagebox.showerror("错误", "请先处理文件")
            return

        self.basic_log.delete(1.0, tk.END)

        if self.word_freq_var.get():
            self.word_frequency_analysis()

        if self.char_count_var.get():
            self.character_count_analysis()

        if self.sentence_count_var.get():
            self.sentence_count_analysis()

    def word_frequency_analysis(self):
        """词频统计"""
        words = jieba.lcut(self.text_content)
        # 去除停用词和空字符串
        words = [word for word in words if word not in self.stopwords and word.strip()]
        word_freq = Counter(words)
        self.basic_log.insert(tk.END, "词频统计 (Top 10):\n")
        for word, freq in word_freq.most_common(10):
            self.basic_log.insert(tk.END, f"{word}: {freq}\n")
        self.basic_log.insert(tk.END, "\n")


    def character_count_analysis(self):
        """字符数统计"""
        char_count = len(self.text_content)
        self.basic_log.insert(tk.END, f"字符数: {char_count}\n\n")

    def sentence_count_analysis(self):
        """句子数统计"""
        sentences = re.split(r'[。!?]', self.text_content)
        sentence_count = len([s for s in sentences if s.strip()])
        self.basic_log.insert(tk.END, f"句子数: {sentence_count}\n\n")

    def perform_advanced_analysis(self):
        """执行高级分析"""
        if not self.text_content:
            messagebox.showerror("错误", "请先处理文件")
            return

        self.advanced_log.delete(1.0, tk.END)

        if self.pos_tagging_var.get():
            self.pos_tagging_analysis()

        if self.named_entity_var.get():
            self.named_entity_recognition()

        if self.keyword_extraction_var.get():
            self.keyword_extraction_analysis()

    def pos_tagging_analysis(self):
        """词性标注"""
        words = pseg.cut(self.text_content)
        # 去除停用词和空字符串
        words = [(word, flag) for word, flag in words if word not in self.stopwords and word.strip()]
        self.advanced_log.insert(tk.END, "词性标注 (前20个):\n")
        for word, flag in words[:20]:
            self.advanced_log.insert(tk.END, f"{word}/{flag} ")
        self.advanced_log.insert(tk.END, "\n\n")

    def named_entity_recognition(self):
        """命名实体识别"""
        words = pseg.cut(self.text_content)
        # 去除停用词和空字符串
        words = [(word, flag) for word, flag in words if word not in self.stopwords and word.strip()]
        entities = []
        for word, flag in words:
            if flag.startswith('n'):
                entities.append(word)
        self.advanced_log.insert(tk.END, "命名实体识别 (Top 10):\n")
        for entity in Counter(entities).most_common(10):
            self.advanced_log.insert(tk.END, f"{entity[0]}: {entity[1]}\n")
        self.advanced_log.insert(tk.END, "\n")

    def keyword_extraction_analysis(self):
        """关键词提取"""
        keywords = jieba.analyse.extract_tags(self.text_content, topK=10)
        self.advanced_log.insert(tk.END, "关键词提取 (Top 10):\n")
        for keyword in keywords:
            self.advanced_log.insert(tk.END, f"{keyword} ")
        self.advanced_log.insert(tk.END, "\n\n")

    def perform_visualization(self):
        """执行可视化"""
        if not self.text_content:
            messagebox.showerror("错误", "请先处理文件")
            return

        self.visualization_log.delete(1.0, tk.END)

        if self.word_cloud_var.get():
            self.generate_word_cloud()

        if self.word_freq_chart_var.get():
            self.generate_word_freq_chart()

        if self.word_cooccurrence_var.get():
            self.generate_word_cooccurrence_network()

    def generate_word_cloud(self):
        """生成词云图"""
        import matplotlib.font_manager as fm

        words = jieba.lcut(self.text_content)
        # 去除停用词和空字符串
        words = [word for word in words if word not in self.stopwords and word.strip()]
        word_freq = Counter(words)

        # 将词频转换为字符串
        text = ' '.join([word for word, freq in word_freq.items() for _ in range(freq)])

        # 设置中文字体
        font_path = 'simhei.ttf'  # 请确保这个字体文件在您的系统中或项目目录下
        font_prop = fm.FontProperties(fname=font_path)

        wordcloud = WordCloud(font_path=font_path, width=800, height=400,
                              background_color="white").generate(text)

        plt.figure(figsize=(10, 5))
        plt.imshow(wordcloud, interpolation="bilinear")
        plt.axis("off")
        plt.title("词云图", fontproperties=font_prop)
        plt.savefig("wordcloud.png")
        plt.close()

        self.visualization_log.insert(tk.END, "词云图已生成,保存为 wordcloud.png\n")

    def generate_word_freq_chart(self):
        """生成词频柱状图"""
        import matplotlib.font_manager as fm

        words = jieba.lcut(self.text_content)
        # 去除停用词和空字符串
        words = [word for word in words if word not in self.stopwords and word.strip()]
        word_freq = Counter(words)
        top_words = dict(word_freq.most_common(20))

        # 设置中文字体
        font_path = 'simhei.ttf'  # 请确保这个字体文件在您的系统中或项目目录下
        font_prop = fm.FontProperties(fname=font_path)

        plt.figure(figsize=(12, 6))
        plt.bar(top_words.keys(), top_words.values())
        plt.title("词频柱状图 (Top 20)", fontproperties=font_prop)
        plt.xlabel("词语", fontproperties=font_prop)
        plt.ylabel("频率", fontproperties=font_prop)
        plt.xticks(rotation=45, ha='right', fontproperties=font_prop)
        plt.tight_layout()
        plt.savefig("word_freq_chart.png")
        plt.close()

        self.visualization_log.insert(tk.END, "词频柱状图已生成,保存为 word_freq_chart.png\n")

    def generate_word_cooccurrence_network(self):
        """生成词语共现网络"""
        import matplotlib.font_manager as fm

        words = jieba.lcut(self.text_content)
        # 去除停用词和空字符串
        words = [word for word in words if word not in self.stopwords and word.strip()]
        word_pairs = [(words[i], words[i+1]) for i in range(len(words)-1)]
        pair_freq = Counter(word_pairs)

        G = nx.Graph()
        for (word1, word2), freq in pair_freq.most_common(50):
            G.add_edge(word1, word2, weight=freq)

        # 设置中文字体
        font_path = 'simhei.ttf'  # 请确保这个字体文件在您的系统中或项目目录下
        font_prop = fm.FontProperties(fname=font_path)

        plt.figure(figsize=(12, 8))
        pos = nx.spring_layout(G)
        nx.draw(G, pos, with_labels=True, node_color='lightblue', node_size=1000,
                font_size=16, font_weight='bold', font_family=font_prop.get_name())
        edge_weights = nx.get_edge_attributes(G, 'weight')
        nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_weights)
        plt.title("词语共现网络", fontproperties=font_prop)
        plt.axis('off')
        plt.tight_layout()
        plt.savefig("word_cooccurrence_network.png")
        plt.close()

        self.visualization_log.insert(tk.END, "词语共现网络已生成,保存为 word_cooccurrence_network.png\n")

    def perform_nlp_tasks(self):
        """执行NLP任务"""
        if not self.text_content:
            messagebox.showerror("错误", "请先处理文件")
            return

        self.nlp_log.delete(1.0, tk.END)

        if self.text_classification_var.get():
            self.text_classification()

        if self.sentiment_analysis_var.get():
            self.sentiment_analysis()

        if self.text_summarization_var.get():
            self.text_summarization()

    def text_classification(self):
        """文本分类"""
        # 这里使用一个简单的基于关键词的分类方法
        keywords = {
            '科技': ['人工智能', '区块链', '5G', '量子计算', '物联网'],
            '体育': ['足球', '篮球', '网球', '奥运会', '世界杯'],
            '娱乐': ['电影', '音乐', '明星', '综艺', '演唱会'],
            '经济': ['股票', '基金', '投资', '金融', '经济']
        }

        words = jieba.lcut(self.text_content)
        # 去除停用词
        words = [word for word in words if word not in self.stopwords]
        word_freq = Counter(words)

        scores = {}
        for category, kw_list in keywords.items():
            score = sum(word_freq.get(kw, 0) for kw in kw_list)
            scores[category] = score

        predicted_category = max(scores, key=scores.get)
        self.nlp_log.insert(tk.END, f"文本分类结果:{predicted_category}\n\n")

    def sentiment_analysis(self):
        """情感分析"""
        # 这里使用一个简单的基于词典的情感分析方法
        positive_words = set(['喜欢', '高兴', '快乐', '美好', '优秀', '棒', '好'])
        negative_words = set(['讨厌', '失望', '难过', '糟糕', '差劲', '坏', '不好'])

        words = jieba.lcut(self.text_content)
        # 去除停用词
        words = [word for word in words if word not in self.stopwords]
        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 = "正面"
        elif positive_count < negative_count:
            sentiment = "负面"
        else:
            sentiment = "中性"

        self.nlp_log.insert(tk.END, f"情感分析结果:{sentiment}\n")
        self.nlp_log.insert(tk.END, f"正面词数量:{positive_count}\n")
        self.nlp_log.insert(tk.END, f"负面词数量:{negative_count}\n\n")

    def text_summarization(self):
        """文本摘要"""
        sentences = re.split(r'[。!?]', self.text_content)
        sentences = [sent.strip() for sent in sentences if sent.strip()]

        # 使用TF-IDF来计算句子的重要性
        vectorizer = TfidfVectorizer()
        tfidf_matrix = vectorizer.fit_transform(sentences)

        # 计算每个句子的平均TF-IDF分数
        sentence_scores = tfidf_matrix.sum(axis=1).A1

        # 选择前3个最重要的句子作为摘要
        top_sentences_indices = sentence_scores.argsort()[-3:][::-1]
        summary = [sentences[i] for i in sorted(top_sentences_indices)]

        self.nlp_log.insert(tk.END, "文本摘要:\n")
        for sent in summary:
            self.nlp_log.insert(tk.END, f"{sent}。\n")
        self.nlp_log.insert(tk.END, "\n")

    def run(self):
        """运行程序"""
        self.window.mainloop()


if __name__ == "__main__":
    analyzer = ChineseTextAnalyzer()
    analyzer.run()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值