带有句子的定向图作为节点usnig Python

时间:2017-04-27 06:41:20

标签: python directed-graph popularity

我想实现一个流行功能,用于在我的项目中对多个句子进行排名。 我想知道如何来实现有向图,每个节点代表一个句子,如果句子之间的余弦相似度超过阈值,则它们之间存在边缘。

1 个答案:

答案 0 :(得分: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)
祝你好运!

相关问题