通过依存关系生成邻接矩阵

import spacy
from tqdm import  tqdm
import numpy as np

# In[8]
def adj_dependcy_tree(argments, max_length=80):
    nlp = spacy.load('en')
    depend = []
    depend1 = []
    doc = nlp(str(argments))
    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(80)
    for (i, j) in depend1:
        if i>=80 or j>=80:
            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


# In[8]
# adj1, d1, dsn1 = adj_dependcy_tree('I love eating apple')
# d1 
posted @ 2021-05-10 21:23  douzujun  阅读(226)  评论(0编辑  收藏  举报