import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict
# 准备数据
text = "社会网络分析方法是由社会学家根据数学方法﹑图论等发展起来的定量分析方法,近年来,该方法在职业流动、城市化对个体幸福的影响、世界政治和经济体系、国际贸易等领域广泛应用,并发挥了重要作用。社会网络分析是社会学领域比较成熟的分析方法,社会学家们利用它可以比较得心应手地来解释一些社会学问题。许多学科的专家如经济学、管理学等领域的学者们在新经济时代——知识经济时代,面临许多挑战时,开始考虑借鉴其他学科的研究方法,社会网络分析就是其中的一种。"
# 分词
keywords = text.split()
# 创建一个空的无向图
G = nx.Graph()
# 添加节点(关键词)
nodes = set()
for keyword in keywords:
nodes.add(keyword)
G.add_nodes_from(nodes)
# 添加边(共现关系)
edges = defaultdict(int)
for i in range(len(keywords)):
keyword1 = keywords[i]
for j in range(i+1, len(keywords)):
keyword2 = keywords[j]
if keyword1 in text and keyword2 in text:
edges[(keyword1, keyword2)] += 1
G.add_edges_from(edges)
# 绘制社会网络图
pos = nx.spring_layout(G)
labels = {node: pos[node] for node in G.nodes()}
nx.draw_networkx_nodes(G, pos, node_size=100, node_color='lightblue')
nx.draw_networkx_edges(G, pos, width=1, alpha=0.5)
nx.draw_networkx_labels(G, labels, font_size=16, font_family='sans-serif')
plt.axis('off')
plt.show()
Python networkx 实现 社会网络分析 关键词共现
最新推荐文章于 2024-04-27 01:12:39 发布