import jieba import re from gensim.models import Word2Vec
# ========== 1. 数据准备 ========== withopen('zh_comments.txt', encoding='utf-8') as f: texts = [line.strip() for line in f if line.strip()]
# 加载自定义词典 jieba.load_userdict('custom_words.txt')
# 分词 + 清洗 sentences = [] for text in texts: # 1. 分词 words = jieba.lcut(text) # 2. 去停用词、单字、纯标点 cleaned = [ w for w in words iflen(w) > 1 andnot re.match(r'^[\W\d]+$', w) and w notin stopwords ] sentences.append(cleaned)
import networkx as nx import matplotlib.pyplot as plt
defplot_similar_network(model, target_words, topn=8, threshold=0.5): G = nx.Graph() for target in target_words: if target notin model.wv: continue for word, score in model.wv.most_similar(target, topn=topn): if score >= threshold: G.add_edge(target, word, weight=score) # 布局 pos = nx.spring_layout(G, k=0.8, iterations=50, seed=42) # 画图 fig, ax = plt.subplots(figsize=(14, 10)) node_sizes = [800if n in target_words else200for n in G.nodes()] edge_widths = [G[u][v]['weight'] * 3for u, v in G.edges()] nx.draw_networkx_nodes(G, pos, node_size=node_sizes, node_color=['#ff5cb3'if n in target_words else'#6e5cff' for n in G.nodes()], alpha=0.85, ax=ax) nx.draw_networkx_edges(G, pos, width=edge_widths, edge_color='rgba(0, 212, 255, 0.4)', ax=ax) nx.draw_networkx_labels(G, pos, font_size=10, font_color='#fff', ax=ax) ax.set_title('Word2Vec 相似词关系图', fontsize=15) ax.axis('off') plt.tight_layout() plt.savefig('similar_words_network.png', dpi=150) return G