【发布时间】:2016-07-01 14:38:23
【问题描述】:
我正在尝试计算一组中所有名词对之间的最短路径。我有很多这样的名词组,组大小不同。最大的一组包含大约 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 之间,这就是我必须输出的数字(或它的倒数,表示这条路径上的步数)。
我们将不胜感激帮助或建议如何做到这一点。
【问题讨论】:
标签: python nlp nltk similarity wordnet