【发布时间】:2017-12-02 23:14:35
【问题描述】:
我编写了一个代码来下载列表中单词的同义词locations。但由于一个词可以有多种含义,我使用另一个列表meaning 来指向我想要的那个词的含义的序列号。然后根据找到的这些同义词计算单词之间的相似度,然后将它们保存在一个文件中。
from nltk.corpus import wordnet as wn
from textblob import Word
from textblob.wordnet import Synset
locations = ['access', 'airport', 'amenity', 'area', 'atm', 'barrier', 'bay', 'bench', 'boundary', 'bridge', 'building', 'bus', 'cafe', 'car', 'coast', 'continue', 'created', 'defibrillator', 'drinking', 'embankment', 'entrance', 'ferry', 'foot', 'fountain', 'fuel', 'gate', 'golf', 'gps', 'grave', 'highway', 'horse', 'hospital', 'house', 'land', 'layer', 'leisure', 'man', 'market', 'marketplace', 'height', 'name', 'natural', 'exit', 'way', 'park', 'parking', 'place', 'worship', 'playground', 'police', 'station', 'post', 'mail', 'power', 'private', 'public', 'railway', 'ref', 'residential', 'restaurant', 'road', 'route', 'school', 'shelter', 'shop', 'source', 'sport', 'toilet', 'tourism', 'unknown', 'vehicle', 'vending', 'machine', 'village', 'wall', 'waste', 'waterway'];
meaning = [0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 5, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 11, 0, 1, 0, 0, 3, 0, 4, 0, 0, 3, 4, 0, 0, 0, 10, 0, 9, 1, 2, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ncols = len(locations)
nrows = len(locations)
matrix = [[0] * ncols for i in range(nrows)]
for i in range(0,len(locations)):
word1 = Word(locations[i])
SS1 = word1.synsets[meaning[i]]
for j in range(0,len(locations)):
word2 = Word(locations[j])
SS2 = word1.synsets[meaning[j]]
matrix[i][j] = SS1.path_similarity(SS2)
f = open('Similarities.csv', 'w')
print(matrix, file=f)
但是代码给出了以下错误:
SS2 = word1.synsets[meaning[j]]
IndexError: list index out of range
当我打印出i 和j 的值时,我发现它一直打印到 i=0 和 j=36。这意味着当 j=36 时,就会出现错误。列表中索引 36 处的单词是 man,meaning 的索引 36 处的值是 11。
那么,为什么会出现这个错误,我该如何解决呢?
编辑:错误出现在SS2 = word1.synsets[meaning[j]]。应该是SS2 = word2.synsets[meaning[j]]。对不起。
【问题讨论】:
-
print(word1.synsets)的输出是什么? -
看来
word1.synsets没有locations中的项目数那么多。 -
@TomWyllie 它打印出
man这个词的 13 种不同含义。我现在已将屏幕截图包含在问题中。 -
@JoséSánchez
word1.synsets包含 13 个东西,我想提取他第 11 个。我现在已将屏幕截图包含在问题中。 -
为什么是
SS2 = word1.synsets[meaning[j]]而不是SS2 = word2.synsets[meaning[j]]。您确实没有在代码中使用word2。
标签: python list indexoutofboundsexception