自然语言处理demo:基于Python的《三体》文本分析

发布于:2025-03-19 ⋅ 阅读:(17) ⋅ 点赞:(0)

1. 引言

自然语言处理(NLP)是人工智能的重要分支,涉及对文本的理解和处理。在本篇博客中,我们将使用 Python 语言来分析《三体》文本,并总结其设计思想、实现过程及实验结果。

2. 功能介绍

本文实现的主要功能包括:

  • 中文文本分词
  • 关键词提取
  • 词频统计
  • 人物、地名、术语提取
  • 词云生成
  • 关系网络构建

这些功能可用于文本分析、信息抽取以及智能问答系统。

3. 设计思想

NLP 任务通常涉及数据预处理、特征提取和分析。对于中文文本处理,我们采用 jieba 进行分词,并结合 TF-IDF(词频-逆文档频率)算法提取关键词。同时,我们利用 collections.Counter 进行词频统计,并通过 networkx 构建人物关系图。

4. 主要库介绍

在本项目中,我们使用以下 Python 库:

  • jieba:用于中文分词
  • jieba.posseg:用于词性标注,提取人物和地名
  • collections.Counter:用于统计词频
  • re:用于文本清理
  • wordcloud:用于生成词云
  • networkx:用于构建人物关系图
  • matplotlib:用于可视化

4.1 jieba 主要函数

  • jieba.cut(text, cut_all=False):精确模式分词
  • jieba.analyse.extract_tags(text, topK=10, withWeight=False):TF-IDF 关键词提取
  • pseg.cut(text):进行词性标注,提取人名、地名等信息

5. 代码实现

以下是核心代码:

import jieba
import jieba.posseg as pseg
import collections
import matplotlib.pyplot as plt
from wordcloud import WordCloud
import networkx as nx
import re

plt.rcParams['font.sans-serif']=['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False

def read_text(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        return f.read()

def segment_text(text):
    words = jieba.cut(text)
    return [word for word in words if len(word) > 1 and re.match(r"[一-龥]+", word)]

def extract_entities(text):
    persons, locations, terms = [], [], []
    words = pseg.cut(text)
    for word, flag in words:
        if len(word) > 1 and re.match(r"[一-龥]+", word):
            if flag == "nr":  # 人名
                persons.append(word)
            elif flag == "ns":  # 地名
                locations.append(word)
            elif flag in ["n", "nz"]:  # 术语(如科技、概念)
                terms.append(word)
    return persons, locations, terms

def plot_wordcloud(word_counts):
    wc = WordCloud(font_path="msyh.ttc", background_color="white", width=800, height=400)
    wc.generate_from_frequencies(dict(word_counts))
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")
    plt.show()

def generate_relation_graph(person_list):
    G = nx.Graph()
    for i in range(len(person_list) - 1):
        G.add_edge(person_list[i], person_list[i + 1])
    plt.figure(figsize=(8, 8))
    nx.draw(G, with_labels=True, node_color='lightblue', edge_color='gray', font_size=10)
    plt.show()

if __name__ == "__main__":
    file_path = "santi.txt"  # 《三体》文本文件路径
    text = read_text(file_path)
    words = segment_text(text)
    top_words = collections.Counter(words).most_common(20)
    print("高频词:", top_words)
    persons, locations, terms = extract_entities(text)
    print("人物:", collections.Counter(persons).most_common(10))
    print("地名:", collections.Counter(locations).most_common(10))
    print("术语:", collections.Counter(terms).most_common(10))
    plot_wordcloud(top_words)
    generate_relation_graph(persons[:100])

6. 测试数据与结果

柱状图

词云

关系图

场景

人名

科技

输出

高频词: [('一个', 3065), ('没有', 2137), ('他们', 1692), ('我们', 1561), ('自己', 1371), ('这个', 1354), ('程心', 1324), ('已经', 1284), ('现在', 1276), ('世界', 1241), ('罗辑', 1200), ('什么', 1182), ('可能', 1180), ('看到', 1118), ('知道', 1099), ('地球', 963), ('人类', 937), ('太空', 935), ('三体', 906), ('宇宙', 889), ('可以', 867), (' 就是', 856), ('太阳', 779), ('这样', 763), ('不是', 726)]
主要人物: [('罗辑', 1035), ('文明', 566), ('叶文洁', 469), ('关一帆', 259), ('史强', 228), ('迪亚兹', 201), ('丁仪', 168), ('泰勒', 153), ('阳光', 147), ('明白', 119), (' 庄颜', 119), ('苏醒', 115), ('王子', 98), ('常伟思', 89), ('伊文斯', 87)]
科幻场景: [('太阳', 779), ('东西', 521), ('北海', 329), ('城市', 286), ('黑洞', 98), ('澳大利亚', 98), ('海洋', 81), ('维度', 79), ('中国', 75), ('欧洲', 71), ('美国', 69), ('王国', 69), ('美丽', 67), ('山杉', 53), ('深水', 53)]
特殊武器: [('智子', 459), ('水滴', 310), ('光粒', 44), ('二向箔', 1)]


网站公告

今日签到

点亮在社区的每一天
去签到