python 中的文本挖掘图句子

textmining graph sentences in python

我正在尝试解决 python 中的一个文本挖掘问题,其中包括:

目标:通过将段落标记为句子来创建由节点(句子)组成的图,它们的边就是它们的相似性。

这一点都不新鲜,但问题的症结在互联网上并没有得到很好的处理。因此,从段落中获取句子后,有趣的一点是计算句子(所有组合)之间的相似性矩阵以绘制图形。

是否有任何包可以简单地执行多个向量之间的相似性?即使使用给定的字符串列表也可以制作相似性图...

一个可重现的例子:

# tokenize into sentences
>>> from nltk import tokenize
>>> p = "Help my code works. The graph isn't still connected. The code computes the relationship in a graph. "
>>> sentences=tokenize.sent_tokenize(p)
  ['Help my code works.', "The graph isn't still connected.", 'The code computes the relationship in a graph.']
>>> len (sentences)
3

# compute similarity with dice coeffcient.
>>>def dice_coefficient(a, b):
    """dice coefficient 2nt/na + nb."""
    a_bigrams = set(a)
    b_bigrams = set(b)
    overlap = len(a_bigrams & b_bigrams)
    return overlap * 2.0/(len(a_bigrams) + len(b_bigrams)
>>>dice_coefficient(sentences[1],sentences[2])
0.918918918918919

所以,有了这个功能,我可以手动完成,然后用节点和边制作图形。但总的来说,一个全局的解决方案(有 n 个句子)是最好的。

有什么建议吗?

下面的列表理解创建了一个元组列表,其中前两个元素是索引,最后一个是相似度:

edges = [(i,j,dice_coefficient(x,y)) 
         for i,x in enumerate(sentences) 
         for j,y in enumerate(sentences) if i < j]

您现在可以删除低于某个阈值的边,并将剩余的边转换为具有 networkx:

的图形
import networkx as nx
G = nx.Graph()
G.add_edges_from((i,j) for i,j,sim in edges if sim >= THRESHOLD)