2017-04-27 38 views
0

我想實現一個在我的項目中排列多個句子的熱門功能。 我想知道如何實現一個有向圖,每個節點代表一個句子和一個邊緣存在於它們之間,如果句子之間的餘弦相似度超過一個閾值。以節點usnig作爲句子的有向圖Python

回答

1

下面是一段代碼,它將繪製一個包含n個節點的圖形,其中n是列表中提供的字符串的數量。邊緣以格式(i,j)提供,其中i,j是與字符串列表中的索引相對應的節點編號。在這個例子中,(0,2)對應於'Some'和'Strings'之間的邊。

由於您正在根據某個閾值連接節點,因此您的邊界列表將對應於以下類似的內容:[[(x,y) for y in range(len(words)) if similarity(words[x],words[y]) < threshold][0] for x in range(len(words))]其中similarity()是您檢查相似度所定義的函數。

from igraph import * 

words = ['Some', 'Random', 'Strings','Okay'] #Whatever your strings would be 

n_nodes = len(words) #Would be equal to the amount of words you have 

g = Graph(directed=True) 
layout = g.layout('kk') 
edges = [(n,n+1) for n in range(n_nodes-1)] #Connects each node to the next, replace this with your own adjacency tuples 

g.add_vertices(n_nodes) #Add the nodes 
g.add_edges(edges) #Add the edges 

plot(g, bbox=(500,500),margin=30, vertex_label = words) 

祝你好運!

相關問題