Python實現(xiàn)中文文本處理與分析程序的示例詳解
在當(dāng)今信息爆炸的時代,文本數(shù)據(jù)的處理與分析成為了數(shù)據(jù)科學(xué)領(lǐng)域的重要課題。特別是對于中文文本,由于其獨特的語言特性和復(fù)雜的語法結(jié)構(gòu),處理起來更具挑戰(zhàn)性。為了解決這個問題,我們開發(fā)了一款基于Python的中文文本處理與分析程序。該程序集成了文件操作、基礎(chǔ)分析、高級分析、可視化以及自然語言處理(NLP)等多種功能,旨在為用戶提供一個全面、易用的文本處理工具。本文將對該程序的主要功能進行詳細解析,并通過實戰(zhàn)應(yīng)用展示其強大的處理能力。
一、程序概述
該程序是一個集文本處理、分析、可視化及NLP任務(wù)于一體的綜合工具。它利用Python的多個強大庫,如jieba、matplotlib、networkx、pandas和scikit-learn等,實現(xiàn)了文本的分詞、詞性標(biāo)注、命名實體識別、關(guān)鍵詞提取、詞頻統(tǒng)計、字符數(shù)統(tǒng)計、句子數(shù)統(tǒng)計、詞云圖生成、詞頻柱狀圖生成、詞語共現(xiàn)網(wǎng)絡(luò)生成以及文本分類、情感分析和文本摘要等功能。程序提供了一個簡潔直觀的圖形用戶界面(GUI),使得用戶無需深入了解底層實現(xiàn)即可輕松完成文本處理與分析任務(wù)。
二、主要功能解析
2.1 文件操作
程序提供了文件操作功能,允許用戶選擇輸入文件和輸出文件,以及停用詞文件。用戶可以通過點擊“瀏覽”按鈕來選擇文件,程序會自動讀取文件內(nèi)容并在日志區(qū)域顯示相關(guān)信息。對于停用詞文件,程序會讀取文件中的詞語并將其作為停用詞,用于后續(xù)的分詞和文本處理任務(wù)。
2.2 基礎(chǔ)分析
基礎(chǔ)分析功能包括詞頻統(tǒng)計、字符數(shù)統(tǒng)計和句子數(shù)統(tǒng)計。用戶可以通過勾選相應(yīng)的復(fù)選框來選擇需要執(zhí)行的分析任務(wù)。
- 詞頻統(tǒng)計:程序會對文本進行分詞,并統(tǒng)計每個詞語的出現(xiàn)頻率。用戶可以選擇顯示前N個高頻詞語(默認為前10個)。
- 字符數(shù)統(tǒng)計:程序會統(tǒng)計文本的總字符數(shù),并在日志區(qū)域顯示結(jié)果。
- 句子數(shù)統(tǒng)計:程序會根據(jù)標(biāo)點符號將文本拆分成句子,并統(tǒng)計句子的總數(shù)。
2.3 高級分析
高級分析功能包括詞性標(biāo)注、命名實體識別和關(guān)鍵詞提取。這些功能依賴于jieba庫的詞性標(biāo)注和關(guān)鍵詞提取模塊。
- 詞性標(biāo)注:程序會對文本進行分詞和詞性標(biāo)注,并顯示前N個詞語及其詞性(默認為前20個)。
- 命名實體識別:程序會識別文本中的命名實體(如人名、地名、機構(gòu)名等),并統(tǒng)計每個實體的出現(xiàn)頻率。用戶可以選擇顯示前N個高頻實體(默認為前10個)。
- 關(guān)鍵詞提取:程序會提取文本中的關(guān)鍵詞,并顯示前N個關(guān)鍵詞(默認為前10個)。
2.4 可視化
可視化功能包括詞云圖生成、詞頻柱狀圖生成和詞語共現(xiàn)網(wǎng)絡(luò)生成。這些功能依賴于matplotlib和networkx庫。
- 詞云圖:程序會根據(jù)詞頻生成詞云圖,直觀展示文本中的高頻詞語。
- 詞頻柱狀圖:程序會生成詞頻柱狀圖,展示前N個高頻詞語及其頻率(默認為前20個)。
- 詞語共現(xiàn)網(wǎng)絡(luò):程序會根據(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)鍵詞提取模塊。
- 文本分類:程序會根據(jù)文本內(nèi)容將其分類到預(yù)定義的類別中。這里我們使用了一個簡單的基于關(guān)鍵詞的分類方法作為示例。
- 情感分析:程序會分析文本的情感傾向(正面、負面或中性)。這里我們使用了一個簡單的基于詞典的情感分析方法作為示例。
- 文本摘要:程序會生成文本的摘要,提取出文本中的關(guān)鍵信息。這里我們使用了TF-IDF算法來計算句子的重要性,并選擇重要性最高的N個句子作為摘要(默認為前3個)。
三、實戰(zhàn)應(yīng)用
3.1 文本預(yù)處理
首先,我們需要對文本進行預(yù)處理,包括去除標(biāo)點符號、停用詞等。這些步驟對于后續(xù)的文本分析和可視化至關(guān)重要。
# 選擇輸入文件和停用詞文件 analyzer.select_input_file() analyzer.select_stopwords_file() # 處理文件 analyzer.process_file()
3.2 基礎(chǔ)分析
接下來,我們可以執(zhí)行一些基礎(chǔ)分析任務(wù),如詞頻統(tǒng)計、字符數(shù)統(tǒng)計和句子數(shù)統(tǒng)計。
# 執(zhí)行基礎(chǔ)分析 analyzer.word_frequency_analysis() analyzer.character_count_analysis() analyzer.sentence_count_analysis()
3.3 高級分析
在基礎(chǔ)分析的基礎(chǔ)上,我們可以進一步執(zhí)行高級分析任務(wù),如詞性標(biāo)注、命名實體識別和關(guān)鍵詞提取。
# 執(zhí)行高級分析 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ù)實現(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庫進行文本處理。jieba是一個中文文本分詞工具,支持三種分詞模式:精確模式、全模式和搜索引擎模式。此外,jieba還提供了詞性標(biāo)注、命名實體識別和關(guān)鍵詞提取等功能。
4.3 數(shù)據(jù)可視化
程序利用matplotlib和networkx庫進行數(shù)據(jù)可視化。matplotlib是Python的一個繪圖庫,提供了豐富的繪圖函數(shù)和接口,使得繪制各種靜態(tài)、動態(tài)和交互式的圖表變得簡單快捷。networkx是一個用于創(chuàng)建、操作和研究復(fù)雜網(wǎng)絡(luò)的Python包,支持創(chuàng)建、繪制和分析各種類型的網(wǎng)絡(luò)圖。
4.4 NLP任務(wù)
程序利用scikit-learn庫執(zhí)行NLP任務(wù)。scikit-learn是一個開源的機器學(xué)習(xí)庫,提供了大量的算法和工具,用于數(shù)據(jù)挖掘和數(shù)據(jù)分析。在NLP任務(wù)中,我們主要使用了TF-IDF算法和簡單的分類、情感分析方法。
五、總結(jié)與展望
本文詳細解析了一款基于Python的中文文本處理與分析程序的主要功能及其實現(xiàn)方式。該程序提供了一個簡潔直觀的GUI界面,使得用戶無需深入了解底層實現(xiàn)即可輕松完成文本處理與分析任務(wù)。通過集成文件操作、基礎(chǔ)分析、高級分析、可視化以及NLP任務(wù)等多種功能,該程序能夠滿足用戶在文本處理與分析方面的多種需求。
未來,我們將繼續(xù)優(yōu)化和完善該程序,增加更多的文本處理和分析功能,提高程序的性能和穩(wěn)定性。同時,我們也將探索更多的NLP任務(wù)和應(yī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="分析選項") 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)計", 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)計", 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)計", 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="詞性標(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="命名實體識別", 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="可視化選項") 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選項") 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)} 個停用詞\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") # 去除標(biāo)點符號 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"已去除停用詞和標(biāo)點符號,處理后共 {len(filtered_words)} 個詞\n") else: self.file_log.insert(tk.END, "已去除標(biā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("錯誤", "請先處理文件") 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)計""" 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)計 (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)計""" 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)計""" 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í)行高級分析""" 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): """詞性標(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個):\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): """關(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("錯誤", "請先處理文件") 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' # 請確保這個字體文件在您的系統(tǒ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' # 請確保這個字體文件在您的系統(tǒ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' # 請確保這個字體文件在您的系統(tǒ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("錯誤", "請先處理文件") 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): """文本分類""" # 這里使用一個簡單的基于關(guān)鍵詞的分類方法 keywords = { '科技': ['人工智能', '區(qū)塊鏈', '5G', '量子計算', '物聯(lián)網(wǎng)'], '體育': ['足球', '籃球', '網(wǎng)球', '奧運會', '世界杯'], '娛樂': ['電影', '音樂', '明星', '綜藝', '演唱會'], '經(jīng)濟': ['股票', '基金', '投資', '金融', '經(jīng)濟'] } 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): """情感分析""" # 這里使用一個簡單的基于詞典的情感分析方法 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 = "負面" 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"負面詞數(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來計算句子的重要性 vectorizer = TfidfVectorizer() tfidf_matrix = vectorizer.fit_transform(sentences) # 計算每個句子的平均TF-IDF分?jǐn)?shù) 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()
到此這篇關(guān)于Python實現(xiàn)中文文本處理與分析程序的示例詳解的文章就介紹到這了,更多相關(guān)Python中文文本處理與分析內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python api構(gòu)建tensorrt加速模型的步驟詳解
小編個人認為python比c++更容易讀并且已經(jīng)有很多包裝很好的科學(xué)運算庫(numpy,scikit等),今天通過本文給大家分享Python api構(gòu)建tensorrt加速模型的步驟,感興趣的朋友一起看看吧2021-09-09Python實現(xiàn)數(shù)據(jù)的序列化操作詳解
在日常開發(fā)中,對數(shù)據(jù)進行序列化和反序列化是常見的數(shù)據(jù)操作,Python提供了兩個模塊方便開發(fā)者實現(xiàn)數(shù)據(jù)的序列化操作,即?json?模塊和?pickle?模塊。本文就為大家詳細講解這兩個模塊的使用,需要的可以參考一下2022-07-07