【问题标题】:Why am I getting `list index out of range` error?为什么会出现“列表索引超出范围”错误?
【发布时间】: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

当我打印出ij 的值时,我发现它一直打印到 i=0 和 j=36。这意味着当 j=36 时,就会出现错误。列表中索引 36 处的单词是 manmeaning 的索引 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


【解决方案1】:

len(word1.synsets) 返回 8,type(word1.synsets) 返回列表。所以它是一个索引为 0 到 7 的列表。

您的列表“含义”在索引 36 处包含 11。因此,当您的循环到达 word1.synsets[11] 时,您会得到索引超出范围错误。

就像 Jose 说的,7 是你在“意义”中可以拥有的最大 int。

【讨论】:

  • len(word1.synsets) 为我返回 13(我已编辑问题以在问题中包含屏幕截图)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-04
  • 2016-08-22
  • 2014-04-10
  • 1970-01-01
  • 2019-09-06
  • 2015-09-12
相关资源
最近更新 更多