#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Filename :depency_matix.py
@Description :
@Datatime :2021/10/08 11:03:42
@Author :qtxu
@Version :v1.0
@function:通过依存关系生成邻接矩阵
'''
import spacy
from tqdm import tqdm
import numpy as np
def adj_dependcy_tree(argments, max_length):
# nlp = spacy.load('en')
nlp = spacy.load("en_core_web_sm")
depend = []
depend1 = []
doc = nlp(str(argments)) # doc表示当前的sentence
print(doc)
d = {}
i = 0
for(_, token) in enumerate(doc):
if str(token) in d.keys():
continue
d[str(token)] = i
i = i+1
for token in doc:
depend.append((token.text, token.head.text)) #将关系对加入depend[]
# print("token.text: ",token.text)
# print("token.head.text:", token.head.text)
depend1.append((d[str(token)], d[str(token.head)]))
ze = np.identity(max_length) # np.identity(n) 创建n*n的矩阵
for(i,j) in depend1:
if i >= max_length or j >= max_length:
continue
ze[i][j] = 1
# D = np.array(np.sum(ze, axis=1))
# D = np.matrix(np.diag(D))
# DSN = np.sqrt(D** -1)
# DN = D ** -1
# return ze, DN, DSN
return ze
if __name__ == "__main__":
cur_length = 5 # 长度大于等于句子长度即可
argments = "I love eating apple."
print(adj_dependcy_tree(argments,max_length=cur_length) )
程序结果:
[[1. 1. 0. 0. 0.] [0. 1. 0. 0. 0.] [0. 1. 1. 0. 0.] [0. 0. 1. 1. 0.] [0. 1. 0. 0. 1.]]



