前言

Python 3.11.8 NetworkX 3.3 matplotlib 3.9.2

同义词文件

  • qbit_synonym.txt
怎=>怎,怎么,怎样 i-pod, i pod => ipod 事,事儿 事儿,事情 gpt,chatgpt

代码

  • code
# encoding: utf8 # author: qbit # date: 2024-08-20 # summary: 使用 NetworkX 展示 Elasticsearch 同义词文件 import matplotlib.pyplot as plt import networkx as nx plt.rcParams['font.sans-serif'] = ['SimHei'] # 避免中文乱码 G = nx.DiGraph() # 创建一个有向图 with open('qbit_synonym.txt', mode='r', encoding='utf8') as f: for line in f: line = line.strip() if not line: continue if '=>' in line: # 单向 idx = line.index('=>') part1 = line[ : idx] part2 = line[idx+2: ] else: # 双向 part1 = part2 = line for u in part1.split(','): u = u.strip() if not u: continue for v in part2.split(','): v = v.strip() if not v: continue G.add_edge(u, v) for node in G.nodes(): print(node, end=f" -> {node}") for item in nx.descendants(G, node): print(f",{item}", end='') print() pos = nx.circular_layout(G) nx.draw_networkx(G, pos, alpha=0.5) # 绘制图形 plt.show()
  • 可以切换自己需要的布局
# pos = nx.planar_layout(G) # pos = nx.random_layout(G) # pos = nx.shell_layout(G) # pos = nx.spring_layout(G) # pos = nx.spectral_layout(G) # pos = nx.spiral_layout(G)

结果

  • 控制台打印
怎 -> 怎,怎么,怎样 怎么 -> 怎么 怎样 -> 怎样 i-pod -> i-pod,ipod ipod -> ipod i pod -> i pod,ipod 事 -> 事,事儿,事情 事儿 -> 事儿,事,事情 事情 -> 事情,事,事儿 gpt -> gpt,chatgpt chatgpt -> chatgpt,gpt
  • 图片展示
    image.png
本文出自 qbit snap

qbit
276 声望279 粉丝

引用和评论

0 条评论