计算 Python 中 window 中单词之间的距离

Calculate distance between words in a window in Python

我想建立一个距离矩阵(稀疏矩阵),它类似于共现矩阵。在大小为 7 的 window 中,我想计算两个特定单词之间的距离并依次移动 window。

以此为例:

anarchism/NOUN NIL NIL NIL term/NOUN NIL abuse/NOUN NIL NIL NIL NIL working/NOUN class/NOUN radicals/NOUN

这是我有的名词,我把不相关的词替换成"NIL"(只是表示距离),保留名词和形容词。

我想计算 (term, abuse), (working, class), (working, radicals), (class, radicals) 之间的距离。其他距离未计算,因为它们超出 window 尺寸 7.

我想为 sparseMatrix 获取矩阵记录,如下所示:

    i       j     dis
1 term    abuse    2
2 working class    1
3 working radicals 2
4 class   radicals 1

Python有什么有效的方法吗,我的语料库大小可能是 10G+。

非常感谢!

所以基本上,您希望获得 7 或更小的距离。您可以通过以下过程(伪代码)轻松完成此操作:

for each word index:
  skip if word[index] is NIL
  for offset from 1 to 7:
    stop if index+offset is past last element
    skip if word[index+offset] is NIL
    make triplet (word[index], word[index+offset], offset)

将它填入scipy sparse matrix应该很容易(您还需要为每个离散单词分配一个ID,因为scipy矩阵索引必须是整数)。

编辑:不知道为什么我把 6 放在那里……当然应该是 7