最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)中文文本處理與分析程序的示例詳解

 更新時(shí)間:2025年07月20日 11:14:25   作者:智算菩薩  
在當(dāng)今信息爆炸的時(shí)代,文本數(shù)據(jù)的處理與分析成為了數(shù)據(jù)科學(xué)領(lǐng)域的重要課題,本文將使用Python開發(fā)一款基于Python的中文文本處理與分析程序,希望對(duì)大家有所幫助

在當(dāng)今信息爆炸的時(shí)代,文本數(shù)據(jù)的處理與分析成為了數(shù)據(jù)科學(xué)領(lǐng)域的重要課題。特別是對(duì)于中文文本,由于其獨(dú)特的語言特性和復(fù)雜的語法結(jié)構(gòu),處理起來更具挑戰(zhàn)性。為了解決這個(gè)問題,我們開發(fā)了一款基于Python的中文文本處理與分析程序。該程序集成了文件操作、基礎(chǔ)分析、高級(jí)分析、可視化以及自然語言處理(NLP)等多種功能,旨在為用戶提供一個(gè)全面、易用的文本處理工具。本文將對(duì)該程序的主要功能進(jìn)行詳細(xì)解析,并通過實(shí)戰(zhàn)應(yīng)用展示其強(qiáng)大的處理能力。

一、程序概述

該程序是一個(gè)集文本處理、分析、可視化及NLP任務(wù)于一體的綜合工具。它利用Python的多個(gè)強(qiáng)大庫,如jieba、matplotlib、networkx、pandas和scikit-learn等,實(shí)現(xiàn)了文本的分詞、詞性標(biāo)注、命名實(shí)體識(shí)別、關(guān)鍵詞提取、詞頻統(tǒng)計(jì)、字符數(shù)統(tǒng)計(jì)、句子數(shù)統(tǒng)計(jì)、詞云圖生成、詞頻柱狀圖生成、詞語共現(xiàn)網(wǎng)絡(luò)生成以及文本分類、情感分析和文本摘要等功能。程序提供了一個(gè)簡潔直觀的圖形用戶界面(GUI),使得用戶無需深入了解底層實(shí)現(xiàn)即可輕松完成文本處理與分析任務(wù)。

二、主要功能解析

2.1 文件操作

程序提供了文件操作功能,允許用戶選擇輸入文件和輸出文件,以及停用詞文件。用戶可以通過點(diǎn)擊“瀏覽”按鈕來選擇文件,程序會(huì)自動(dòng)讀取文件內(nèi)容并在日志區(qū)域顯示相關(guān)信息。對(duì)于停用詞文件,程序會(huì)讀取文件中的詞語并將其作為停用詞,用于后續(xù)的分詞和文本處理任務(wù)。

2.2 基礎(chǔ)分析

基礎(chǔ)分析功能包括詞頻統(tǒng)計(jì)、字符數(shù)統(tǒng)計(jì)和句子數(shù)統(tǒng)計(jì)。用戶可以通過勾選相應(yīng)的復(fù)選框來選擇需要執(zhí)行的分析任務(wù)。

  • 詞頻統(tǒng)計(jì):程序會(huì)對(duì)文本進(jìn)行分詞,并統(tǒng)計(jì)每個(gè)詞語的出現(xiàn)頻率。用戶可以選擇顯示前N個(gè)高頻詞語(默認(rèn)為前10個(gè))。
  • 字符數(shù)統(tǒng)計(jì):程序會(huì)統(tǒng)計(jì)文本的總字符數(shù),并在日志區(qū)域顯示結(jié)果。
  • 句子數(shù)統(tǒng)計(jì):程序會(huì)根據(jù)標(biāo)點(diǎn)符號(hào)將文本拆分成句子,并統(tǒng)計(jì)句子的總數(shù)。

2.3 高級(jí)分析

高級(jí)分析功能包括詞性標(biāo)注、命名實(shí)體識(shí)別和關(guān)鍵詞提取。這些功能依賴于jieba庫的詞性標(biāo)注和關(guān)鍵詞提取模塊。

  • 詞性標(biāo)注:程序會(huì)對(duì)文本進(jìn)行分詞和詞性標(biāo)注,并顯示前N個(gè)詞語及其詞性(默認(rèn)為前20個(gè))。
  • 命名實(shí)體識(shí)別:程序會(huì)識(shí)別文本中的命名實(shí)體(如人名、地名、機(jī)構(gòu)名等),并統(tǒng)計(jì)每個(gè)實(shí)體的出現(xiàn)頻率。用戶可以選擇顯示前N個(gè)高頻實(shí)體(默認(rèn)為前10個(gè))。
  • 關(guān)鍵詞提取:程序會(huì)提取文本中的關(guān)鍵詞,并顯示前N個(gè)關(guān)鍵詞(默認(rèn)為前10個(gè))。

2.4 可視化

可視化功能包括詞云圖生成、詞頻柱狀圖生成和詞語共現(xiàn)網(wǎng)絡(luò)生成。這些功能依賴于matplotlib和networkx庫。

  • 詞云圖:程序會(huì)根據(jù)詞頻生成詞云圖,直觀展示文本中的高頻詞語。
  • 詞頻柱狀圖:程序會(huì)生成詞頻柱狀圖,展示前N個(gè)高頻詞語及其頻率(默認(rèn)為前20個(gè))。
  • 詞語共現(xiàn)網(wǎng)絡(luò):程序會(huì)根據(jù)詞語的共現(xiàn)關(guān)系生成共現(xiàn)網(wǎng)絡(luò)圖,展示詞語之間的關(guān)聯(lián)程度。

2.5 NLP任務(wù)

NLP任務(wù)功能包括文本分類、情感分析和文本摘要。這些功能依賴于scikit-learn庫和jieba庫的關(guān)鍵詞提取模塊。

  • 文本分類:程序會(huì)根據(jù)文本內(nèi)容將其分類到預(yù)定義的類別中。這里我們使用了一個(gè)簡單的基于關(guān)鍵詞的分類方法作為示例。
  • 情感分析:程序會(huì)分析文本的情感傾向(正面、負(fù)面或中性)。這里我們使用了一個(gè)簡單的基于詞典的情感分析方法作為示例。
  • 文本摘要:程序會(huì)生成文本的摘要,提取出文本中的關(guān)鍵信息。這里我們使用了TF-IDF算法來計(jì)算句子的重要性,并選擇重要性最高的N個(gè)句子作為摘要(默認(rèn)為前3個(gè))。

三、實(shí)戰(zhàn)應(yīng)用

3.1 文本預(yù)處理

首先,我們需要對(duì)文本進(jìn)行預(yù)處理,包括去除標(biāo)點(diǎn)符號(hào)、停用詞等。這些步驟對(duì)于后續(xù)的文本分析和可視化至關(guān)重要。

# 選擇輸入文件和停用詞文件 
analyzer.select_input_file() 
analyzer.select_stopwords_file() 


# 處理文件 
analyzer.process_file()

3.2 基礎(chǔ)分析

接下來,我們可以執(zhí)行一些基礎(chǔ)分析任務(wù),如詞頻統(tǒng)計(jì)、字符數(shù)統(tǒng)計(jì)和句子數(shù)統(tǒng)計(jì)。

# 執(zhí)行基礎(chǔ)分析 
analyzer.word_frequency_analysis() 
analyzer.character_count_analysis() 
analyzer.sentence_count_analysis()

3.3 高級(jí)分析

在基礎(chǔ)分析的基礎(chǔ)上,我們可以進(jìn)一步執(zhí)行高級(jí)分析任務(wù),如詞性標(biāo)注、命名實(shí)體識(shí)別和關(guān)鍵詞提取。

# 執(zhí)行高級(jí)分析 
analyzer.pos_tagging_analysis() 
analyzer.named_entity_recognition() 
analyzer.keyword_extraction_analysis()

3.4 可視化

為了更直觀地展示文本分析結(jié)果,我們可以生成詞云圖、詞頻柱狀圖和詞語共現(xiàn)網(wǎng)絡(luò)。

# 執(zhí)行可視化 
analyzer.generate_word_cloud() 
analyzer.generate_word_freq_chart() 
analyzer.generate_word_cooccurrence_network()

3.5 NLP任務(wù)

最后,我們可以執(zhí)行一些NLP任務(wù),如文本分類、情感分析和文本摘要。

# 執(zhí)行NLP任務(wù) 
analyzer.text_classification() 
analyzer.sentiment_analysis() 
analyzer.text_summarization()

四、技術(shù)實(shí)現(xiàn)

4.1 GUI構(gòu)建

程序利用tkinter庫構(gòu)建GUI界面。tkinter是Python的標(biāo)準(zhǔn)GUI庫,提供了豐富的控件和布局管理器,使得構(gòu)建復(fù)雜的GUI界面變得簡單直觀。

4.2 文本處理

程序利用jieba庫進(jìn)行文本處理。jieba是一個(gè)中文文本分詞工具,支持三種分詞模式:精確模式、全模式和搜索引擎模式。此外,jieba還提供了詞性標(biāo)注、命名實(shí)體識(shí)別和關(guān)鍵詞提取等功能。

4.3 數(shù)據(jù)可視化

程序利用matplotlib和networkx庫進(jìn)行數(shù)據(jù)可視化。matplotlib是Python的一個(gè)繪圖庫,提供了豐富的繪圖函數(shù)和接口,使得繪制各種靜態(tài)、動(dòng)態(tài)和交互式的圖表變得簡單快捷。networkx是一個(gè)用于創(chuàng)建、操作和研究復(fù)雜網(wǎng)絡(luò)的Python包,支持創(chuàng)建、繪制和分析各種類型的網(wǎng)絡(luò)圖。

4.4 NLP任務(wù)

程序利用scikit-learn庫執(zhí)行NLP任務(wù)。scikit-learn是一個(gè)開源的機(jī)器學(xué)習(xí)庫,提供了大量的算法和工具,用于數(shù)據(jù)挖掘和數(shù)據(jù)分析。在NLP任務(wù)中,我們主要使用了TF-IDF算法和簡單的分類、情感分析方法。

五、總結(jié)與展望

本文詳細(xì)解析了一款基于Python的中文文本處理與分析程序的主要功能及其實(shí)現(xiàn)方式。該程序提供了一個(gè)簡潔直觀的GUI界面,使得用戶無需深入了解底層實(shí)現(xiàn)即可輕松完成文本處理與分析任務(wù)。通過集成文件操作、基礎(chǔ)分析、高級(jí)分析、可視化以及NLP任務(wù)等多種功能,該程序能夠滿足用戶在文本處理與分析方面的多種需求。

未來,我們將繼續(xù)優(yōu)化和完善該程序,增加更多的文本處理和分析功能,提高程序的性能和穩(wěn)定性。同時(shí),我們也將探索更多的NLP任務(wù)和應(yīng)用場(chǎng)景,為用戶提供更加全面和強(qiáng)大的文本處理與分析工具。希望本文能夠?yàn)樽x者提供有益的參考和借鑒,推動(dòng)中文文本處理與分析技術(shù)的發(fā)展和應(yīng)用。

展示如下:

目前完整代碼:

# -*- 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="基礎(chǔ)分析")

        options_frame = ttk.LabelFrame(basic_tab, text="分析選項(xiàng)")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.word_freq_var = tk.BooleanVar()
        word_freq_check = ttk.Checkbutton(options_frame, text="詞頻統(tǒng)計(jì)", 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="字符數(shù)統(tǒng)計(jì)", 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="句子數(shù)統(tǒng)計(jì)", 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="高級(jí)分析")

        options_frame = ttk.LabelFrame(advanced_tab, text="分析選項(xiàng)")
        options_frame.pack(fill=tk.X, padx=5, pady=5)

        self.pos_tagging_var = tk.BooleanVar()
        pos_tagging_check = ttk.Checkbutton(options_frame, text="詞性標(biāo)注", 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="命名實(shí)體識(shí)別", 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="關(guān)鍵詞提取", 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="可視化選項(xiàng)")
        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="詞語共現(xiàn)網(wǎng)絡(luò)", 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任務(wù)")

        options_frame = ttk.LabelFrame(nlp_tab, text="NLP選項(xiàng)")
        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="執(zhí)行NLP任務(wù)", 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)} 個(gè)停用詞\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("錯(cuò)誤", "請(qǐng)選擇輸入文件")
            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)} 個(gè)字符\n")

            # 去除標(biāo)點(diǎn)符號(hào)
            self.text_content = ''.join(char for char in self.text_content if char not in self.punctuation)

            # 如果有停用詞,進(jìn)行分詞并去除停用詞
            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"已去除停用詞和標(biāo)點(diǎn)符號(hào),處理后共 {len(filtered_words)} 個(gè)詞\n")
            else:
                self.file_log.insert(tk.END, "已去除標(biāo)點(diǎn)符號(hào)\n")
        except Exception as e:
            self.file_log.insert(tk.END, f"文件讀取失敗: {str(e)}\n")

    def perform_basic_analysis(self):
        """執(zhí)行基礎(chǔ)分析"""
        if not self.text_content:
            messagebox.showerror("錯(cuò)誤", "請(qǐng)先處理文件")
            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):
        """詞頻統(tǒng)計(jì)"""
        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, "詞頻統(tǒng)計(jì) (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):
        """字符數(shù)統(tǒng)計(jì)"""
        char_count = len(self.text_content)
        self.basic_log.insert(tk.END, f"字符數(shù): {char_count}\n\n")

    def sentence_count_analysis(self):
        """句子數(shù)統(tǒng)計(jì)"""
        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"句子數(shù): {sentence_count}\n\n")

    def perform_advanced_analysis(self):
        """執(zhí)行高級(jí)分析"""
        if not self.text_content:
            messagebox.showerror("錯(cuò)誤", "請(qǐng)先處理文件")
            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):
        """詞性標(biāo)注"""
        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, "詞性標(biāo)注 (前20個(gè)):\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):
        """命名實(shí)體識(shí)別"""
        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, "命名實(shí)體識(shí)別 (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):
        """關(guān)鍵詞提取"""
        keywords = jieba.analyse.extract_tags(self.text_content, topK=10)
        self.advanced_log.insert(tk.END, "關(guān)鍵詞提取 (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):
        """執(zhí)行可視化"""
        if not self.text_content:
            messagebox.showerror("錯(cuò)誤", "請(qǐng)先處理文件")
            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)

        # 將詞頻轉(zhuǎn)換為字符串
        text = ' '.join([word for word, freq in word_freq.items() for _ in range(freq)])

        # 設(shè)置中文字體
        font_path = 'simhei.ttf'  # 請(qǐng)確保這個(gè)字體文件在您的系統(tǒng)中或項(xiàng)目目錄下
        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))

        # 設(shè)置中文字體
        font_path = 'simhei.ttf'  # 請(qǐng)確保這個(gè)字體文件在您的系統(tǒng)中或項(xiàng)目目錄下
        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):
        """生成詞語共現(xiàn)網(wǎng)絡(luò)"""
        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)

        # 設(shè)置中文字體
        font_path = 'simhei.ttf'  # 請(qǐng)確保這個(gè)字體文件在您的系統(tǒng)中或項(xiàng)目目錄下
        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("詞語共現(xiàn)網(wǎng)絡(luò)", fontproperties=font_prop)
        plt.axis('off')
        plt.tight_layout()
        plt.savefig("word_cooccurrence_network.png")
        plt.close()

        self.visualization_log.insert(tk.END, "詞語共現(xiàn)網(wǎng)絡(luò)已生成,保存為 word_cooccurrence_network.png\n")

    def perform_nlp_tasks(self):
        """執(zhí)行NLP任務(wù)"""
        if not self.text_content:
            messagebox.showerror("錯(cuò)誤", "請(qǐng)先處理文件")
            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):
        """文本分類"""
        # 這里使用一個(gè)簡單的基于關(guān)鍵詞的分類方法
        keywords = {
            '科技': ['人工智能', '區(qū)塊鏈', '5G', '量子計(jì)算', '物聯(lián)網(wǎng)'],
            '體育': ['足球', '籃球', '網(wǎng)球', '奧運(yùn)會(huì)', '世界杯'],
            '娛樂': ['電影', '音樂', '明星', '綜藝', '演唱會(huì)'],
            '經(jīng)濟(jì)': ['股票', '基金', '投資', '金融', '經(jīng)濟(jì)']
        }

        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"文本分類結(jié)果:{predicted_category}\n\n")

    def sentiment_analysis(self):
        """情感分析"""
        # 這里使用一個(gè)簡單的基于詞典的情感分析方法
        positive_words = set(['喜歡', '高興', '快樂', '美好', '優(yōu)秀', '棒', '好'])
        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 = "負(fù)面"
        else:
            sentiment = "中性"

        self.nlp_log.insert(tk.END, f"情感分析結(jié)果:{sentiment}\n")
        self.nlp_log.insert(tk.END, f"正面詞數(shù)量:{positive_count}\n")
        self.nlp_log.insert(tk.END, f"負(fù)面詞數(shù)量:{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來計(jì)算句子的重要性
        vectorizer = TfidfVectorizer()
        tfidf_matrix = vectorizer.fit_transform(sentences)

        # 計(jì)算每個(gè)句子的平均TF-IDF分?jǐn)?shù)
        sentence_scores = tfidf_matrix.sum(axis=1).A1

        # 選擇前3個(gè)最重要的句子作為摘要
        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):
        """運(yùn)行程序"""
        self.window.mainloop()


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

到此這篇關(guān)于Python實(shí)現(xiàn)中文文本處理與分析程序的示例詳解的文章就介紹到這了,更多相關(guān)Python中文文本處理與分析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 詳解Python字典小結(jié)

    詳解Python字典小結(jié)

    這篇文章主要介紹了詳解Python字典小結(jié),詳細(xì)的介紹了什么是字典且創(chuàng)建字典和示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2018-10-10
  • 如何使用Python最小二乘法擬合曲線代碼詳解

    如何使用Python最小二乘法擬合曲線代碼詳解

    最小二乘法Least Square Method做為分類回歸算法的基礎(chǔ),有著悠久的歷史,下面這篇文章主要給大家介紹了關(guān)于如何使用Python最小二乘法擬合曲線的相關(guān)資料,需要的朋友可以參考下
    2022-11-11
  • Python使用方法重載實(shí)現(xiàn)訪問者模式

    Python使用方法重載實(shí)現(xiàn)訪問者模式

    這篇文章主要為大家詳細(xì)介紹了Python如何使用方法重載實(shí)現(xiàn)訪問者模式,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2024-12-12
  • Python 用Redis簡單實(shí)現(xiàn)分布式爬蟲的方法

    Python 用Redis簡單實(shí)現(xiàn)分布式爬蟲的方法

    本篇文章主要介紹了Python 用Redis簡單實(shí)現(xiàn)分布式爬蟲的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-11-11
  • 使用AJAX和Django獲取數(shù)據(jù)的方法實(shí)例

    使用AJAX和Django獲取數(shù)據(jù)的方法實(shí)例

    這篇文章主要給大家介紹了關(guān)于使用AJAX和Django獲取數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • 用Python字符畫出了一個(gè)谷愛凌

    用Python字符畫出了一個(gè)谷愛凌

    之前經(jīng)常在網(wǎng)上看到那種由一個(gè)個(gè)字符構(gòu)成的視頻,非常炫酷。本文也將利用Python字符畫一個(gè)最近的冬奧冠軍谷愛凌,感興趣的小伙伴可以學(xué)習(xí)一下
    2022-02-02
  • 使用Python的Flask框架實(shí)現(xiàn)視頻的流媒體傳輸

    使用Python的Flask框架實(shí)現(xiàn)視頻的流媒體傳輸

    這篇文章主要介紹了使用Python的Flask框架實(shí)現(xiàn)視頻的流媒體傳輸,包括從攝像機(jī)獲取幀到web瀏覽器的數(shù)字流傳輸,需要的朋友可以參考下
    2015-03-03
  • python內(nèi)置函數(shù)frozenset()的使用小結(jié)

    python內(nèi)置函數(shù)frozenset()的使用小結(jié)

    本篇文章主要介紹了python內(nèi)置函數(shù)frozenset()的使用小結(jié),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-05-05
  • Windows下python2.7.8安裝圖文教程

    Windows下python2.7.8安裝圖文教程

    這篇文章主要為大家詳細(xì)介紹了Windows下python2.7.8安裝圖文教程,在安裝過程中出現(xiàn)“python不是內(nèi)部或外部命令”提示的解決方法,感興趣的小伙伴們可以參考一下
    2016-05-05
  • Python調(diào)用C/C++動(dòng)態(tài)鏈接庫的方法詳解

    Python調(diào)用C/C++動(dòng)態(tài)鏈接庫的方法詳解

    這篇文章主要介紹了Python調(diào)用C/C++動(dòng)態(tài)鏈接庫的方法,需要的朋友可以參考下
    2014-07-07

最新評(píng)論

吉安县| 平原县| 红原县| 舟山市| 马尔康县| 河津市| 丰城市| 汉源县| 历史| 崇义县| 福清市| 阳新县| 平潭县| 庆云县| 娄烦县| 呼伦贝尔市| 威信县| 福贡县| 南澳县| 邻水| 齐河县| 阜新市| 黔江区| 平湖市| 贵德县| 金堂县| 林西县| 吴旗县| 麻城市| 铜鼓县| 扎囊县| 娄底市| 灌云县| 彰化市| 北流市| 霍城县| 龙里县| 武川县| 新余市| 武宣县| 定日县|