【文本挖掘与文本分析】上机实验三

实验目的和要求

实验

  1. 了解sklearn,gensim可视化主题的基本操作;
  2. 采集四大名著之《红楼梦》进行主题分析
  3. 对《红楼梦》的主题进行可视化
  4. 采集二十大报告进行主题分析;
  5. 对《二十大报告》的主题进行可视化
  1. 数据来源
  1. 《红楼梦》小说
  2. 《二十大报告》

采集红楼梦文本,加载红楼梦人物、停用词和词典,完成以下任务:
1.输出前100个人物的出场次数,然后绘制人物出现词云图,最后再绘制出现次数最多的前20个人物的出场次数柱状图。
2.利用TF-IDF算法,sklearn,gensim对红楼梦进行可视化主题分析
3.基于知识图谱对红楼梦人物关系进行可视化,梳理贾宝玉、林黛玉、薛宝钗和其他人的人物关系。

data = pd.read_excel(“D:\学习\课件\文本挖掘\上机实验\实验三\20230320162359291\Readream\红楼梦数据集.xlsx”)
chapters = data[‘Artical’].tolist()

with open(“D:\学习\课件\文本挖掘\上机实验\实验三\20230320162359291\Readream\红楼梦人物.txt”, “r”, encoding=“utf-8”) as file:
characters = file.read().splitlines()

with open(“D:\学习\课件\文本挖掘\上机实验\实验三\20230320162359291\Readream\红楼梦停用词.txt”, “r”, encoding=“utf-8”) as file:
stopwords = file.read().splitlines()

with open(“D:\学习\课件\文本挖掘\上机实验\实验三\20230320162359291\Readream\红楼梦词典.txt”, “r”, encoding=“utf-8”) as file:
dictionary = file.read().splitlines()
wordcloud = WordCloud(background_color=‘white’, font_path=r"D:\coder\randomnumbers\Keywords_cloud\msyh.ttf",width=800, height=600)

人物出现次数

import pandas as pd
from wordcloud import WordCloud
import matplotlib.pyplot as plt

# 读取数据
data = pd.read_excel("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦数据集.xlsx")
chapters = data['Artical'].tolist()

# 读取人物列表、停用词和词典
with open("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦人物.txt", "r", encoding="utf-8") as file:
    characters = file.read().splitlines()

with open("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦停用词.txt", "r", encoding="utf-8") as file:
    stopwords = file.read().splitlines()

with open("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦词典.txt", "r", encoding="utf-8") as file:
    dictionary = file.read().splitlines()

# 提取人物出现次数
character_counts = {}
for chapter in chapters:
    for character in characters:
        count = chapter.count(character)
        if character in character_counts:
            character_counts[character] += count
        else:
            character_counts[character] = count

# 输出前100个人物的出场次数
sorted_characters = sorted(character_counts.items(), key=lambda x: x[1], reverse=True)[:100]
print("前100个人物的出场次数:")
for character, count in sorted_characters:
    print(f"{character}: {count}")

# 制作词云图
wordcloud = WordCloud(background_color='white', font_path=r"D:\\coder\\randomnumbers\\Keywords_cloud\\msyh.ttf", width=800, height=600)
wordcloud.generate_from_frequencies(character_counts)
plt.figure(figsize=(10, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis('off')
plt.title('红楼梦人物出现词云图')
plt.show()

# 绘制出现次数最多的前20个人物的出场次数柱状图
top20_characters = sorted_characters[:20]
top20_names = [item[0] for item in top20_characters]
top20_counts = [item[1] for item in top20_characters]
plt.figure(figsize=(10, 6))
plt.bar(top20_names, top20_counts, color='skyblue')
plt.xlabel('人物')
plt.ylabel('出场次数')
plt.title('出现次数最多的前20个人物的出场次数')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

在这里插入图片描述
在这里插入图片描述

Top 10关键词

from sklearn.feature_extraction.text import TfidfVectorizer
import re

# 定义需要过滤的无意义词语
meaningless_words = ["说", "道"]

# 自定义分词函数,用于过滤无意义词语
def tokenize(text):
    words = re.findall(r'\b\w+\b', text)
    meaningful_words = [word for word in words if word not in meaningless_words]
    return meaningful_words

# 将章节列表转换为文本字符串
corpus = [' '.join(chapters)]

# 使用TF-IDF向量化器
vectorizer = TfidfVectorizer(stop_words=stopwords, tokenizer=tokenize)
X = vectorizer.fit_transform(corpus)

# 获取特征词列表
feature_names = vectorizer.get_feature_names()

# 获取最重要的词语
indices = X.toarray().argsort(axis=1)[:, ::-1]
top_n = 10  # 取前10个关键词
top_keywords = [feature_names[indices[0, i]] for i in range(top_n)]

print("红楼梦文本的Top 10关键词:")
for i, keyword in enumerate(top_keywords):
    print(f"{i+1}. {keyword}")



红楼梦文本的Top 10关键词:

  1. 说着
  2. 宝玉道
  3. 宝玉笑道
  4. 笑道
  5. 贾母道
  6. 贾政道
  7. 凤姐道
  8. 袭人道
  9. 宝玉听了
  10. 一面说
import networkx as nx
from collections import defaultdict

# 构建人物关系图
G = nx.Graph()

# 使用默认字典以便于处理人物关系
relationships = defaultdict(int)

# 遍历每章节,统计人物之间的共现关系
for chapter in chapters:
    for i in range(len(characters)):
        for j in range(i + 1, len(characters)):
            if characters[i] in chapter and characters[j] in chapter:
                relationships[(characters[i], characters[j])] += 1

# 添加边到图中
for edge, weight in relationships.items():
    G.add_edge(edge[0], edge[1], weight=weight)

# 绘制人物关系图
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, k=0.2)  # 使用Spring布局算法排列节点
nx.draw(G, pos, with_labels=True, node_size=1000, node_color='lightblue', font_size=10, font_weight='bold')
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title('红楼梦人物关系图')
plt.show()

在这里插入图片描述

前20人物出场

import re
from collections import Counter
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 使用微软雅黑字体

# 加载人物列表
with open("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦人物.txt", "r", encoding="utf-8") as file:
    characters = file.read().splitlines()

# 统计人物出场情况
character_freq = Counter(re.findall(r'(%s)' % '|'.join(characters), all_text))

# 选择出现次数最多的前100个人物
top_characters_freq = dict(sorted(character_freq.items(), key=lambda item: item[1], reverse=True)[:100])

# 输出前100个人物的出场次数
for idx, (character, freq) in enumerate(top_characters_freq.items(), 1):
    print(f"{idx}. {character}: {freq}")

# 提取前20个人物和对应的出场次数
top_characters = list(top_characters_freq.keys())[:20]
top_frequencies = list(top_characters_freq.values())[:20]

# 绘制人物出场次数柱状图
plt.figure(figsize=(12, 6))
plt.bar(top_characters, top_frequencies)
plt.title('前20个人物出场情况')
plt.xlabel('人物')
plt.ylabel('出场次数')
plt.xticks(rotation=45)  # 旋转横坐标标签,避免重叠
plt.tight_layout()  # 调整布局以防止标签重叠
plt.show()

在这里插入图片描述

from wordcloud import WordCloud
import matplotlib.pyplot as plt
import re
from collections import Counter

# 加载人物列表
with open("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦人物.txt", "r", encoding="utf-8") as file:
    characters = file.read().splitlines()

# 统计人物出场情况
character_freq = Counter(re.findall(r'(%s)' % '|'.join(characters), all_text))

# 选择出现次数最多的前100个人物
top_characters_freq = dict(sorted(character_freq.items(), key=lambda item: item[1], reverse=True)[:100])

# 输出前100个人物的出场次数
for idx, (character, freq) in enumerate(top_characters_freq.items(), 1):
    print(f"{idx}. {character}: {freq}")

# 绘制人物出现词云图
wordcloud = WordCloud(background_color='white', font_path=r"D:\\coder\\randomnumbers\\Keywords_cloud\\msyh.ttf")
wordcloud.generate_from_frequencies(top_characters_freq)

plt.figure(figsize=(10, 8))
plt.imshow(wordcloud, interpolation='bilinear')
plt.title('人物出现词云图')
plt.axis('off')
plt.show()

# 提取前20个人物和对应的出场次数
top_characters = list(top_characters_freq.keys())[:20]
top_frequencies = list(top_characters_freq.values())[:20]

# 绘制人物出场次数柱状图
plt.figure(figsize=(12, 6))
plt.bar(top_characters, top_frequencies)
plt.title('前20个人物出场情况')
plt.xlabel('人物')
plt.ylabel('出场次数')
plt.xticks(rotation=45)  # 旋转横坐标标签,避免重叠
plt.tight_layout()  # 调整布局以防止标签重叠
plt.show()

人物出现词云

  1. 宝玉: 3810
  2. 凤姐: 1680
  3. 贾母: 1639
  4. 袭人: 1123
  5. 王夫人: 1039
  6. 宝钗: 1002
  7. 贾政: 911
  8. 贾琏: 746
  9. 平儿: 653
  10. 薛姨妈: 446
  11. 紫鹃: 427
  12. 探春: 426
  13. 鸳鸯: 406
  14. 贾珍: 382
  15. 李纨: 366
  16. 晴雯: 340
  17. 尤氏: 336
  18. 刘姥姥: 288
  19. 邢夫人: 280
  20. 小丫头: 279
  21. 薛蟠: 277
  22. 林黛玉: 268
  23. 香菱: 245
  24. 麝月: 232
  25. 贾蓉: 222
  26. 周瑞: 215
  27. 小厮: 207
  28. 贾赦: 190
  29. 贾芸: 185
  30. 惜春: 182
  31. 芳官: 156
  32. 妙玉: 153
  33. 雪雁: 151
  34. 贾环: 146
  35. 林之孝: 142
  36. 迎春: 134
  37. 莺儿: 125
  38. 赵姨娘: 122
  39. 宝蟾: 114
  40. 巧姐: 107
  41. 秦钟: 100
  42. 薛蝌: 99
  43. 贾兰: 94
  44. 秋纹: 93
  45. 茗烟: 88
  46. 尤二姐: 88
  47. 大了: 84
  48. 史湘云: 83
  49. 赖大: 82
  50. 五儿: 80
  51. 司棋: 76
  52. 秦氏: 72
  53. 贾瑞: 68
  54. 旺儿: 68
  55. 贾蔷: 67
  56. 凤丫头: 64
  57. 兴儿: 58
  58. 彩云: 57
  59. 琥珀: 57
  60. 冯紫英: 55
  61. 焙茗: 51
  62. 鲍二: 50
  63. 包勇: 50
  64. 金钏: 48
  65. 门子: 47
  66. 翠缕: 47
  67. 北静王: 45
  68. 丰儿: 43
  69. 李贵: 41
  70. 玉钏儿: 41
  71. 柳家的: 40
  72. 倪二: 39
  73. 张华: 39
  74. 板儿: 38
  75. 小红: 38
  76. 李嬷嬷: 37
  77. 王仁: 36
  78. 坠儿: 36
  79. 甄宝玉: 36
  80. 藕官: 33
  81. 春燕: 33
  82. 尤三姐: 33
  83. 秋桐: 33
  84. 琏二奶奶: 31
  85. 金荣: 29
  86. 贾芹: 29
  87. 石头: 28
  88. 玻璃: 28
  89. 王善保: 28
  90. 大姐: 27
  91. 侍书: 27
  92. 女尼: 27
  93. 李氏: 26
  94. 彩屏: 26
  95. 李纹: 26
  96. 智能: 25
  97. 翠墨: 24
  98. 张道士: 24
  99. 李十儿: 24
  100. 王子腾: 23

在这里插入图片描述

前20个人物关系

import networkx as nx
from collections import defaultdict

# 构建人物关系图
G = nx.Graph()

# 使用默认字典以便于处理人物关系
top20_relationships = defaultdict(int)

# 遍历每章节,统计前20个人物之间的共现关系
for chapter in chapters:
    for i in range(len(top20_characters)):
        for j in range(i + 1, len(top20_characters)):
            if top20_characters[i] in chapter and top20_characters[j] in chapter:
                top20_relationships[(top20_characters[i], top20_characters[j])] += 1

# 添加边到图中
for edge, weight in top20_relationships.items():
    G.add_edge(edge[0], edge[1], weight=weight)

# 绘制人物关系图
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, k=0.2)  # 使用Spring布局算法排列节点
nx.draw(G, pos, with_labels=True, node_size=1000, node_color='lightblue', font_size=10, font_weight='bold')
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title('红楼梦前20个人物关系图')
plt.show()


在这里插入图片描述
在这个图中,人与人之间连线上的数字表示两个人之间的关系强度或者共现次数。在原始代码中,这些数字被命名为weight,代表边的权重。在红楼梦人物关系图中,这些权重可以表示两个人物在文本中共同出现的次数,从而反映了他们之间的关系密切程度或相关性。

如果两个人物之间的数字较大,说明他们在小说中经常一起出现,可能存在密切的关系或者故事情节联系紧密。相反,如果数字较小,则表示两个人物之间的关系不太密切。

import networkx as nx
from collections import defaultdict
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 使用微软雅黑字体

# 构建人物关系图
G = nx.Graph()

# 使用默认字典以便于处理人物关系
relationships = defaultdict(int)

# 遍历每章节,统计人物之间的共现关系
for chapter in chapters:
    for i in range(len(characters)):
        for j in range(i + 1, len(characters)):
            if characters[i] in chapter and characters[j] in chapter:
                relationships[(characters[i], characters[j])] += 1

# 添加边到图中(仅保留关联次数大于等于10的)
for edge, weight in relationships.items():
    if weight >= 15:
        G.add_edge(edge[0], edge[1], weight=weight)

# 绘制人物关系图
plt.figure(figsize=(12, 8))
pos = nx.spring_layout(G, k=0.2)  # 使用Spring布局算法排列节点
nx.draw(G, pos, with_labels=True, node_size=1000, node_color='lightblue', font_size=10, font_weight='bold')
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title('红楼梦人物关系图(关联次数大于等于10)')
plt.show()

在这里插入图片描述

全人物关系图

import networkx as nx
from collections import defaultdict
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 使用微软雅黑字体

# 构建人物关系图
G = nx.Graph()

# 使用默认字典以便于处理人物关系
relationships = defaultdict(int)

# 遍历每章节,统计人物之间的共现关系
for chapter in chapters:
    for i in range(len(characters)):
        for j in range(i + 1, len(characters)):
            if characters[i] in chapter and characters[j] in chapter:
                relationships[(characters[i], characters[j])] += 1

# 添加边到图中(仅保留关联次数大于等于15的)
for edge, weight in relationships.items():
    if weight >= 15:
        G.add_edge(edge[0], edge[1], weight=weight)

# 绘制人物关系图
plt.figure(figsize=(12, 8))
pos = nx.circular_layout(G)  # 使用circular_layout布局算法排列节点
nx.draw(G, pos, with_labels=True, node_size=1000, node_color='lightblue', font_size=10, font_weight='bold')
edge_labels = nx.get_edge_attributes(G, 'weight')
nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
plt.title('红楼梦人物关系图(关联次数大于等于15)')
plt.show()

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

案例

## 加载所需要包
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

from sklearn.feature_extraction.text import CountVectorizer,TfidfTransformer,TfidfVectorizer

## 设置字体
fonts = FontProperties(fname = r"C:\Windows\Fonts\STXIHEI.ttf",size=14)
## 引入3D坐标系
from mpl_toolkits.mplot3d import Axes3D
## 设置pandas显示方式
pd.set_option("display.max_rows",8)

pd.options.mode.chained_assignment = None  # default='warn'

## 设置显示图像的方式
%matplotlib inline
%config InlineBackend.figure_format = "retina"
## 读取停用词
stopword = pd.read_csv("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦停用词.txt",
                       header=None,names = ["Stopwords"])
## 读取红楼梦数据集
Red_df = pd.read_excel("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦数据集.xlsx")
Red_df.head(5)

在这里插入图片描述

import jieba
## 添加自定义词典
jieba.load_userdict("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦词典.txt")
## 对红楼梦全文进行分词
## 数据表的行数
row,col = Red_df.shape
## 预定义列表
Red_df["cutword"] = "cutword"
for ii in np.arange(row):
    ## 分词
    cutwords = list(jieba.cut(Red_df.Artical[ii], cut_all=True))
    ## 去除长度为1的词
    cutwords = pd.Series(cutwords)[pd.Series(cutwords).apply(len)>1]
    ## 去停用词
    cutwords = cutwords[~cutwords.isin(stopword)]
    Red_df.cutword[ii] = cutwords.values
for ii in np.arange(row):   #过滤
    Red_df.cutword[ii] =Red_df.cutword[ii][~(Red_df.cutword[ii]==':“')]
    Red_df.cutword[ii] =Red_df.cutword[ii][~(Red_df.cutword[ii]=='。”')]
    Red_df.cutword[ii] =Red_df.cutword[ii][~(Red_df.cutword[ii]=='?”')]
    Red_df.cutword[ii] =Red_df.cutword[ii][~(Red_df.cutword[ii]=='!”')]
import warnings
warnings.filterwarnings("ignore",category=DeprecationWarning)
warnings.filterwarnings("ignore",category=FutureWarning)

分析红楼梦的人物关系

## 查看几个关键人物在整个书籍中的出现次数的变化
## 读取红楼梦中人物名数据集
role = pd.read_csv("D:\\学习\\课件\\文本挖掘\\上机实验\\实验三\\20230320162359291\\Readream\\红楼梦人物.txt",header=None,names = ["rolename"])
role.head()
## 计算每个角色在书籍中出现的次数
# 将120章的分词结果连接在一起,并计算词频
allcutword = np.concatenate(Red_df.cutword)
allcutword = pd.DataFrame({"word":allcutword})
allcutword = allcutword.groupby(by=["word"])["word"].agg(number=np.size)
allcutword = allcutword.reset_index().sort_values(by="number",ascending=False)
## 计算人物所出现的次数
counts = []
for ii in role.index:
    rolenam = role.rolename[ii]
    number = allcutword["number"][allcutword.word == rolenam]
    counts.append(number.values)

role["counts"] = pd.DataFrame(counts)
## 去除缺失值 和出现次数小于5的人物
role = role[role.counts.notnull()].sort_values(by="counts",ascending=False)
role = role[role.counts > 5].reset_index(drop=True)
print(role.head())

rolename counts
0 宝玉 3862.0
1 凤姐 1680.0
2 贾母 1639.0
3 袭人 1123.0
4 王夫人 1039.0

## 查看前几个关键人物在各章节的走势
rolenumber = np.zeros((10,120))
for kk in np.arange(10):
    # 计算每个人物在各章节出现的次数
    nums = []
    for ii in np.arange(len(Red_df.index)):
        ## 每章节词频
        chapcutword= pd.DataFrame({"word":Red_df.cutword[ii]})
        chapcutword = chapcutword.groupby(by=["word"])["word"].agg(number=np.size)
        chapcutword = chapcutword.reset_index()
        #  一个章节出现次数
        num = chapcutword["number"][chapcutword.word == role.rolename[kk]]
        nums.append(num.values)
    # 一个人的所有章节出现次数
    rolenumber[kk,:] = pd.DataFrame(nums).fillna(0).values[:,0]
## 绘制人物在各个章节出场频次变化图
plt.figure(figsize=(12,8))
for ii in np.arange(6):
    plt.subplot(3,2,ii+1)
    plt.bar(np.arange(120)+1,rolenumber[ii,:],alpha = 1)
    plt.title(role.rolename[ii],fontproperties = fonts,size = 12)
    plt.ylabel("频次",fontproperties = fonts,size = 10)
plt.subplots_adjust(hspace = 0.25,wspace = 0.15)
plt.show()

在这里插入图片描述

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 解决负号'-'显示为方块的问题

## 分析10个人出场的相关性
import seaborn as sns
datacor = np.corrcoef(rolenumber)
datacor = pd.DataFrame(data=datacor,columns=role.rolename[0:10],index=role.rolename[0:10])
## 相关稀疏热力图
plt.figure(figsize=(10,10))
ax = sns.heatmap(datacor,square=True,annot=True,fmt = ".3f",
                 linewidths=.5,cmap="YlGnBu",
                 cbar_kws={"fraction":0.046, "pad":0.03})
ax.set_xticklabels(role.rolename[0:10],fontproperties = fonts)
ax.set_yticklabels(role.rolename[0:10],fontproperties = fonts)
ax.set_title("人物相关性",fontproperties = fonts)
ax.set_xlabel("",fontproperties = fonts)
ax.set_xlabel("",fontproperties = fonts)
plt.show()

在这里插入图片描述

## 根据分词结果,计算人物之间的关系权重,值分析人物出场次数大于100次的人物
## 权重的定义,如果两个人物同时出现在同一章节中,则相应的权重增加1
Red_df.cutword

在这里插入图片描述

rolenew = role[role.counts>100]
rolenew

在这里插入图片描述

## 构建两两之间的关系
from itertools import combinations
relation = combinations(rolenew.rolename,2)

rela = []
weight  = []
for ii in relation:
    rela.append(ii)
    ## 计算两者是之间的权重
    weig = 0
    for kk in np.arange(len(Red_df.index)):
        ## 人物是否同时出现在同一章
        if ((sum(Red_df.cutword[kk] == ii[0]) >1) & (sum(Red_df.cutword[kk] == ii[1]) >1)):
            weig = weig+1
    weight.append(weig)

Red_rela = pd.DataFrame(rela)
Red_rela.columns = ["First","Second"]
Red_rela["weight"] = weight
Red_rela = Red_rela[Red_rela.weight>20].sort_values(by="weight",ascending=False).reset_index(drop = True)
print(Red_rela.head())


在这里插入图片描述

import networkx as nx
## 将人物关系可视化
plt.figure(figsize=(12,12))
## 生成社交网络图
G=nx.Graph()

## 添加边
for ii in Red_rela.index:
    G.add_edge(Red_rela.First[ii],Red_rela.Second[ii],weight = Red_rela.weight[ii] / 120)
    
## 定义两种边
elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.25]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.25]

## 图的布局
pos=nx.circular_layout(G) # positions for all nodes

# nodes根据
nx.draw_networkx_nodes(G,pos,alpha=0.6,node_size=500)

# edges
nx.draw_networkx_edges(G,pos,edgelist=elarge,
                    width=1.5,alpha=0.6,edge_color='r')
nx.draw_networkx_edges(G,pos,edgelist=esmall,
                    width=1,alpha=0.8,edge_color='b',style='dashed')

# labels
nx.draw_networkx_labels(G,pos,font_size=10)

plt.axis('off')
plt.title("《红楼梦》社交网络",FontProperties = fonts)
plt.show() # display

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

## 将人物关系可视化
plt.figure(figsize=(12,12))
## 生成社交网络图
G=nx.Graph()

## 添加边
for ii in Red_rela.index:
    G.add_edge(Red_rela.First[ii],Red_rela.Second[ii],weight = Red_rela.weight[ii] / 120)
    
## 定义两种边
elarge=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] >0.25]
esmall=[(u,v) for (u,v,d) in G.edges(data=True) if d['weight'] <=0.25]

## 图的布局
pos=nx.spring_layout(G) # positions for all nodes

# nodes根据
nx.draw_networkx_nodes(G,pos,alpha=0.6,node_size=500)

# edges
nx.draw_networkx_edges(G,pos,edgelist=elarge,
                    width=1.5,alpha=0.6,edge_color='r')
nx.draw_networkx_edges(G,pos,edgelist=esmall,
                    width=1,alpha=0.8,edge_color='b',style='dashed')

# labels
nx.draw_networkx_labels(G,pos,font_size=10)

plt.axis('off')
plt.title("《红楼梦》社交网络",FontProperties = fonts)
plt.show() # display

在这里插入图片描述

## 计算每个节点的度
Red_degree = pd.DataFrame(list(G.degree))
Red_degree.columns = ["name","degree"]
Red_degree

在这里插入图片描述

Red_degree.sort_values(by="degree",ascending=False).plot(kind = "bar",x="name",y = "degree",figsize=(12,6),legend=False)
plt.xticks(FontProperties = fonts,size = 12)
plt.ylabel("degree")
plt.show()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/489091.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

ubuntu下安装minconda

1.搜索清华源 清华大学开源软件镜像站 | Tsinghua Open Source Mirror 2.搜索conda 3.选一个合适自己的下载到本地 4.将下载的文件传入到ubuntu中 bash Miniconda3-py311_23.11.0-1-Linux-x86_64.sh 安装 5.source ~/.bashrc 激活即可&#xff08;必要步骤&#xff09;

2024年 导出环境依赖requirements.txt

2024年 导出环境依赖 一、前言 有时候需要导出环境依赖&#xff0c;遂记录一下这个短短的步骤 二、具体步骤 1、使用pip进行安装和管理环境 安装导出依赖的库pipreqs pip install pipreqs将环境依赖项导出到当前目录的requirements.txt文件&#xff0c;编码格式用utf-8 …

第15篇:2位数值比较器

Q&#xff1a;本篇我们将实现2位二进制数值比较器逻辑电路&#xff0c;即对2个2位二进制数大小进行比较。 A&#xff1a;数值比较器的基本原理&#xff1a;先对两个数的高位进行比较&#xff0c;若高位相等&#xff0c;再比较低位&#xff0c;低位的比较结果决定两个数的大小。…

自增不再简单:深入探索MySQL自增ID的持久化之道

概述 MySQL中的自增特性估计大家或多或少都是用过。一张表中只能由一个自增字段&#xff0c;通常我们会把它设置为主键&#xff0c;但是随着大家系统越来越分布式&#xff0c;为了一些性能和可扩展性问题&#xff0c;大家目前选择更多的都是分布式ID&#xff08;雪花算法、UUI…

自觉性的力量:在无人监督中追求卓越

一、引言 自觉性&#xff0c;这个看似简单的词汇&#xff0c;却蕴含着巨大的力量。它如同内心的指南针&#xff0c;指引我们在无人监督的情况下&#xff0c;依然能够坚守原则&#xff0c;保持积极向上的态度。在快节奏的现代生活中&#xff0c;自觉性更是成为我们应对挑战、实现…

不可变和可变字符序列使用陷阱

String 使用的陷阱&#xff1a; String 一经初始化后&#xff0c;就不会再改变其内容了。对 String 字符串的操作实际上是对其副本&#xff08;原始拷贝&#xff09;的操作&#xff0c;原来的字符串一点都没有改变。比如&#xff1a; String s "a"; 创建了一个字符…

【创建QT项目】使用向导创建

打开Qt Creator 界面选择 New Project或者选择菜单栏 【文件】-【新建文件或项目】菜单项 弹出New Project对话框&#xff0c;选择Qt Widgets Application&#xff0c; 选择【Choose】按钮&#xff0c;弹出如下对话框 设置项目名称和路径&#xff0c;按照向导进行下一步&#x…

小吉、鲸立、希亦婴儿洗衣机哪个好用?最强机型pk对比!

宝宝衣服的清洗对父母来说都很重要&#xff0c;所以挑选一款适合宝宝的小型洗衣机显得尤为重要。也许有许多人认为&#xff0c;为婴儿购买独立的洗衣机是不必要的&#xff0c;但是你是否了解呢&#xff1f;新生婴儿的肌肤要比成人更脆弱&#xff0c;更易受到感染而受到伤害&…

Ansys Zemax | 在 MATLAB 或 Python 中使用 ZOS-API 进行光线追迹的批次处理

附件下载 联系工作人员获取附件 这篇文章会说明如何在 MATLAB 或 Python 中以 Zemax OpticStudio 应用程式介面 (ZOS-API)处理光线数据库(Ray Database, ZRD)档案&#xff0c;过程中我们将使用ZRDLoader.dll。本文提供了在 Matlab 中批次处理序列光线追迹(一般、归一化、偏振…

python知识点总结(九)

python知识点总结九 1、TCP中socket的实现代码实现TCP协议a、服务端b、客户端&#xff1a; 2、写装饰器&#xff0c;限制函数被执行的频率&#xff0c;如10秒一次3、请实现一个装饰器&#xff0c;通过一次调用函数重复执行5次4、写一个登录装饰器对一下函数进行装饰&#xff0c…

ChatGPT-PDF辅助读论文,实现用gpt对pdf 解析(开源)

文章目录 思路接口代码上传代码pdf转文本代码综合上述步骤完整代码效果 思路 主要为开发者提供一个思路&#xff0c;这里并不是完整的商业项目&#xff0c;只是一时兴起写的一份demo,希望对大家有帮助。 制作一个接口用于上传文件写一个程序把文件上传到上面的接口中对得到的…

深入了解 Vue 3:性能与可用性的巨大提升

摘要&#xff1a;本文深入探讨了 Vue 3 相对于 Vue 2 在性能和可用性方面的重大改进&#xff0c;特别关注了虚拟 DOM 模块的重构&#xff08;静态提升&#xff09;、基于 Proxy 的响应式对象、事件缓存、更好的 Tree Shaking 支持、TypeScript 和 Monorepo 代码组织&#xff0c…

合辑下载 | MatrixOne 与 MySQL 全面对比

前言 MatrixOne是一款高度兼容MySQL语法的HTAP数据库&#xff0c;采用云原生化和存储、计算、事务分离的架构打造了HSTAP超融合数据引擎&#xff0c;实现单一数据库系统同时支持OLTP、OLAP、流计算等多种业务负载。基于MatrixOne高度兼容MySQL的定位&#xff0c;社区的小伙伴在…

使用 NocoDB 一键将各种数据库转换为智能表格

NocoDB 是一款开源的无代码数据库平台&#xff0c;可以进行数据管理和应用开发。它的灵感来自 Airtable&#xff0c;支持与 Airtable 类似的电子表格式交互、关系型数据库 Schema 设计、API 自动生成等特性。 但与 Airtable 相比&#xff0c;NocoDB 完全免费且代码开源&#xf…

柯桥专业会计培训|会计实操做账手工账电脑账出纳报税手把手教

开具纸质发票时&#xff0c;经常有小伙伴纠结发票开票人和复核人的问题。现在全国已施行数电票&#xff0c;这个问题还存在吗&#xff1f;一起来看看~ 暂未规定!! 开票人和复核人不应为同一人&#xff01; 目前&#xff0c;全国大部分城市已基本实现数电票的开票试点&#x…

KIOXIA铠侠CM7系列E3.S双端口NVMe2.0 PCIe5.0 SSD KCM71RJE7T68

KIOXIA 铠侠推出的CM7-R E3.S企业级NVMe读密集型企业级固态硬盘&#xff0c;采用PCIe 5.0和NVMe 2.0技术&#xff0c;性能出色&#xff0c;最高可达2,700K IOPS&#xff08;随机读取&#xff09;和310K IOPS&#xff08;随机写入&#xff09;1 DWPD的耐用性和高达15.36 TB的存储…

ReactNative项目构建分析与思考之RN组件化

传统RN项目对比 ReactNative项目构建分析与思考之react-native-gradle-plugin ReactNative项目构建分析与思考之native_modules.gradle ReactNative项目构建分析与思考之 cli-config 在之前的文章中&#xff0c;已经对RN的默认项目有了一个详细的分析&#xff0c;下面我们来…

vue-office/docx插件实现docx文件预览

1.下包 //预览docx文件 npm install vue-office/docx vue-demi//如果是vue2.6版本或以下还需要额外安装 vue/composition-api2.引入 <template><div>//在src填入文档地址<VueOfficeDocx srchttp://...../xx.docx style"width:80%" rendered"re…

yarn按包的时候报错 ../../../package.json: No license field

运行 yarn config list 然后运行 yarn config set strict-ssl false 之后yarn就成功了

基于ssm学校运动会信息管理系统论文

摘 要 在当今社会上&#xff0c;体育运动越来越普及&#xff0c;参与运动会的人越来越多&#xff0c;但是目前对运动会信息管理还是处于手工记录的时代&#xff0c;这远远满足不了现在用户需求&#xff0c;因此建立一个运动会信息管理系统已经变的非常重要。 本文重点阐述了学…
最新文章