自然语言处理四大名著分析教程
一、程序功能概述
1. 基础功能:中文分词、词频统计、词性标注保存
2. 可视化功能:饼状图/柱状图/关系图/词云生成
3. 高级功能:实体识别(人名/地名/武器)、自定义词典管理
4. 文件操作:TXT文件读写、分析结果持久化存储
二、技术架构设计
1. 系统架构图
[文本输入] → [预处理模块] → [分析引擎] → [可视化模块] → [输出结果]
↑
[自定义词典管理]
2. 模块设计思想
模块化开发:每个功能独立为函数
可扩展性:通过继承BaseAnalyzer类实现功能扩展
可视化分离:使用工厂模式创建不同图表类型
三、核心代码实现
1. 环境准备
python
import jieba
import jieba.analyse
import jieba.posseg as pseg
from collections import Counter
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import networkx as nx
2. 功能函数实现(部分核心代码)
python
class NovelAnalyzer:
def __init__(self, custom_dict=None):
if custom_dict:
jieba.load_userdict(custom_dict)
def segment_text(self, file_path):
分词处理
with open(file_path, 'r', encoding='utf-8') as f:
return [word for word in jieba.cut(f.read())]
def word_frequency(self, words, topN=50):
词频统计
return Counter(words).most_common(topN)
def generate_wordcloud(self, freq_dict, output_path)
词云生成
wc = WordCloud(font_path='msyh.ttc', background_color='white')
wc.generate_from_frequencies(freq_dict)
wc.to_file(output_path)
def entity_recognition(self, text, entity_type):
实体识别
entity_tags = {
'person': ['nr'],
'location': ['ns'],
'weapon': ['nz']
}
return [word for word, flag in pseg.cut(text) if flag in entity_tags[entity_type]]
四、完整代码结构
├── main.py # 主程序入口
├── analyzer.py # 分析器类实现
├── utils
│ ├── visualizer.py # 可视化工具类
│ └── file_handler.py # 文件操作工具类
├── data
│ ├── input # 原始文本
│ └── output # 分析结果
└── config
└── custom_dict.txt # 自定义词典
五、测试与结果分析
1. 测试数据
- 输入文件:`three_kingdoms.txt`(三国演义全文)
- 自定义词典:添加特殊词汇("青龙偃月刀", "赤兔马")
2. 执行命令
python
analyzer = NovelAnalyzer('config/custom_dict.txt')
words = analyzer.segment_text('data/input/three_kingdoms.txt')
person_list = analyzer.entity_recognition(text, 'person')
analyzer.generate_wordcloud(freq_dict, 'output/wordcloud.png')
3. 输出结果示例
词云效果:

人物统计TOP10:
曹操: 1892次
刘备: 1563次
关羽: 1321次
六、技术文档要点
1. 关键库说明
| 库名称 | 用途 | 核心函数 |
|--------------|----------------------|----------------------------|
| jieba | 中文分词 | cut, posseg.cut, analyse |
| matplotlib | 数据可视化 | pie, bar, plot |
| WordCloud | 词云生成 | generate_from_frequencies |
| networkx | 关系网络图 | Graph, draw |
2. 设计注意事项
-内存优化:采用生成器处理大文本
-编码处理:统一使用UTF-8编码
-异常处理:文件操作增加try-except块