如何实现依据依存关系构造邻接矩阵(有向图)
'''
@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_core_web_sm")
depend = []
depend1 = []
doc = nlp(str(argments))
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))
depend1.append((d[str(token)], d[str(token.head)]))
ze = np.identity(max_length)
for(i,j) in depend1:
if i >= max_length or j >= max_length:
continue
ze[i][j] = 1
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.]]
|