如何用NLTK、WordNet、相似度计算一个组中所有名词对之间的最短路径?

How to calculate shortest paths between all pairs of nouns in a group with NLTK, WordNet, and similarity?

我正在尝试计算一组中所有名词对之间的最短路径。我有许多这样的名词组,它们的组大小不同。最大的一组包含大约 250 个名词。输入是一个包含名词的 txt 文件,每个名词占一行。作为 txt 文件的输出应列出具有相应最短路径的所有名词对。

我是 python 和 NLTK 的新手,在这里和其他来源进行了大量搜索、多次试验和错误之后,这就是我想出的代码:

import nltk
from nltk.corpus import wordnet as wn

listSim = []
with open("words-input.txt", "rU") as wordList1:
    myList1 = [line.rstrip('\n') for line in wordList1]
    for word1 in myList1:
        with open("words-input2.txt", "rU") as wordList2:
            myList2 = [line.rstrip('\n') for line in wordList2]
            for word2 in myList2:
                wordFromList1 = wn.synsets(word1)
                wordFromList2 = wn.synsets(word2)
                if wordFromList1 and wordFromList2:
                    s = 1/(wordFromList1[0].path_similarity(wordFromList2[0]))
                    sym = (word1, word2, s)
                    listSim.append(sym)

print (listSim)
with open("words-output.txt", "w") as text_file:
    print (listSim, file=text_file)

(注意,我无法成功迭代同一个txt文件,所以我复制了一个,上面的'words-input.txt'和'words-input2.txt'代码包含相同顺序的同一组名词。)

我的代码的问题是它只计算名词的第一个同义词集(第一个意思 - n#1)之间的最短路径。例如,如果最短路径出现在 noun1 的 n#3 和 noun2 的 n#5 之间,这就是我必须输出的数字(或者它的倒数,代表这条路径上的步数)。

如能提供帮助或建议,我们将不胜感激。

下面应该为你做的,我只提供相关部分。

from itertools import product

for word1 in myList1:
    for word2 in myList2:
        list1 = wn.synsets(word1)
        list2 = wn.synsets(word2)

        sList = [ss1.path_similarity(ss2) for ss1, ss2 in product(list1, list2)]

        best = sorted(sList, reverse=True)[0]
        listSim.append((word1, word2, best))