一、共现语义网络原理
共现语义网络是用于表示词与词之间的语义关系的一种网络理论,由美国人工智能专家司马贺在1973年提出的。其原理就是以词语为网络的结点,以沟通结点的共现次数表示词语之间的语义关系,构成一个彼此相互联系的网络,以达到理解自然语言句子的语义关系。
二、中文分词
构建共现语义网络首先要进行分词,通常可以使用Jieba和Snownlp做中文分词。笔者使用的数据是自己在招聘网站采集的岗位招聘要求信息数据,使用Jieba分词后保存到源数据,并使用pandas库把整个文件保存为csv文件,方便后续使用。部分数据如下:
三、构建共现语义网络
1. 导入需要的包
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from tkinter import _flatten
2. 构建共现语义矩阵
先用pandas库把分词数据读取到jupyter notebook中,并选出分词后的数据。
df = pd.read_csv('电商岗位数据(分词后).csv')
content = df['分词']
对分词进行词频统计并选取前50关键词作为构建共现矩阵的关键词。
cut_word_list = list(map(lambda x: ''.join(x), content.tolist()))
content_str = ' '.join(cut_word_list).split()
word_fre = pd.Series(_flatten(content_str)).value_counts() # 统计词频
word_fre[:50]
词频统计结果:
keywords = word_fre[:50].index
keywords
使用numpy设置共现语义的初始矩阵。
matrix = np.zeros((len(keywords)+1)*(len(keywords)+1)).reshape(len(keywords)+1, len(keywords)+1).astype(str)
matrix[0][0] = np.NaN
matrix[1:, 0] = matrix[0, 1:] = keywords
matrix
计算关键词之间的共现次数,共现规则为关键词之间的位置距离不超过1。
cont_list = [cont.split() for cont in cut_word_list]
for i, w1 in enumerate(word_fre[:50].index):
for j, w2 in enumerate(word_fre[:50].index):
count = 0
for cont in cont_list:
if w1 in cont and w2 in cont:
if abs(cont.index(w1)-cont.index(w2)) == 0 or abs(cont.index(w1)-cont.index(w2)) == 1:
count += 1
matrix[i+1][j+1] = count
保存为csv文件。
kwdata = pd.DataFrame(data=matrix)
kwdata.to_csv('关键词共现矩阵.csv', index=False, header=None, encoding='utf-8-sig')
3. 绘制共现语义网络
读取关键词共现矩阵文件。
df = pd.read_csv('关键词共现矩阵.csv')
选取前20个关键词作为实验对象。
df.index = df.iloc[:, 0].tolist()
df_ = df.iloc[:20, 1:21]
df_.astype(int)
绘制共现语义网络图。
plt.figure(figsize=(10, 10))
graph1 = nx.from_pandas_adjacency(df_)
nx.draw(graph1, with_labels=True, node_color='yellow', font_size=25, edge_color='blue')
plt.savefig('共现网络图.jpg')
关键词之间的连线越多,说明共现的次数越多。本文使用Python做的共现语义图并没有实现展示关键词之间的共现次数,有能力的大佬可以尝试做一下能输出关键词共现次数的共现语义网络图。尽管现在很多软件能实现共现语义网络图,笔者也用过几个画共现语义网络的软件,但当数据量大的时候,往往电脑会卡死。