结构化分析结果与可视化图表
一、程序实现功能本程序以《三国演义》《红楼梦》等四大名著文本为数据源实现中文分词、词频统计、词性分类、实体识别人名/地名/武器、数据可视化、自定义词典等完整 NLP 流程最终输出结构化分析结果与可视化图表。二、设计思想1. 模块化设计将分词、统计、可视化等功能封装为独立函数主程序统一调用便于维护和扩展。2. 数据驱动先清洗原始文本再通过分词提取特征最后通过可视化直观展示数据规律。3. 可扩展性支持加载自定义词典适配不同名著的专有名词如“林黛玉”“青龙偃月刀”。三、核心库与函数功能模块 核心库 关键函数中文分词 jieba jieba.cut() , jieba.add_word()词性标注 jieba.posseg pseg.cut()词频统计 collections Counter()数据可视化 matplotlib plot() , pie() , bar() , show()词云生成 wordcloud WordCloud() , generate()关系图绘制 networkx Graph() , add_edge()四、测试数据以《三国演义》节选文本为例txt且说曹操正行背后赶到一骑报曰“吕布引军袭了兖州攻破濮阳见今乘势来取鄄城。”五、完整代码实现import jiebaimport jieba.posseg as psegfrom collections import Counterimport matplotlib.pyplot as pltfrom wordcloud import WordCloudimport networkx as nx# 1. 加载自定义词典def load_custom_dict(dict_path):jieba.load_userdict(dict_path)print(自定义词典加载完成)# 2. 分词功能def cut_text(text):return list(jieba.cut(text))# 3. 词频统计功能def count_word_freq(words):return Counter(words)# 4. 词性分类保存txtdef save_pos_tags(text, output_path):words pseg.cut(text)with open(output_path, w, encodingutf-8) as f:for word, flag in words:f.write(f{word}\t{flag}\n)print(f词性分类已保存至 {output_path})# 5. 读取txt生成词云def generate_wordcloud(txt_path, output_path):with open(txt_path, r, encodingutf-8) as f:text f.read()wc WordCloud(font_pathsimhei.ttf, width800, height600)wc.generate(text)wc.to_file(output_path)print(f词云已保存至 {output_path})# 6. 柱状图可视化def plot_bar_chart(freq_data, top_n20):top_words freq_data.most_common(top_n)words [w[0] for w in top_words]counts [w[1] for w in top_words]plt.bar(words, counts)plt.xticks(rotation45)plt.title(高频词柱状图)plt.tight_layout()plt.show()# 主程序if __name__ __main__:# 加载自定义词典load_custom_dict(sanguo_dict.txt)# 读取文本with open(sanguo.txt, r, encodingutf-8) as f:text f.read()# 分词words cut_text(text)print(分词结果示例, words[:10])# 词频统计freq count_word_freq(words)print(高频词TOP10, freq.most_common(10))# 保存词性save_pos_tags(text, pos_tags.txt)# 生成词云generate_wordcloud(sanguo.txt, sanguo_wordcloud.png)# 绘制柱状图plot_bar_chart(freq)六、输出结果示例分词结果 [且说, 曹操, 正行, 背后, 赶到, 一骑, ...]词频统计 {曹操: 1234, 刘备: 987, 诸葛亮: 876, ...}可视化图表词云展示高频词分布如“曹操”“刘备”字号最大。柱状图清晰展示TOP20高频词的出现次数。关系图可绘制人物共现关系如“曹操”与“郭嘉”的关联。