0

我收到一个错误“列表超出范围。虽然我找到了这个错误的相反方式,但我知道如何解决这个错误。 在此处输入图像描述

4

5 回答 5

2

for loop正如大家所建议的那样,问题不在于你。问题在于“the”synset这个词,因为the”的同义词集条目不存在。您可以使用以下代码替换您的代码:

for i in range(len(words)):
    synset = wordnet.synsets(words[i])
    if synset:
        print ("Synonym of the word "+words[i]+" in the list is: "+synset[0].lemmas()[0].name())
    else:
        print ("Synonym of the word "+words[i]+" not found in the list")

输出:

Synonym of the word After in the list is: after
Synonym of the word getting in the list is: acquiring
Synonym of the word the not found in the list
Synonym of the word proper in the list is: proper
Synonym of the word co-ordinates in the list is: coordinate

希望上面的代码能帮到你!

于 2021-08-26T09:18:00.787 回答
2

len在本例中为 5,因此 range 正在创建一个从 0 到 5 的范围,而您的列表索引从 0 到 4。

您可以将该行重写为:

for i in range(len(words)-1):

否则,如果您只需要单词而不是索引,则可以编写

for word in words:

最后,如果您需要单词和索引,您可以使用enumerate()

for i, word in enumerate(words, start=0):
于 2021-08-26T07:50:30.487 回答
1

您不需要使用 len() 函数或 range() 函数。你可以使用:

for i in words:
  synset = wordnet.synsets(i)
  print(i + synset)
于 2021-08-26T07:53:51.093 回答
0

尝试将范围设置为:

len(words) - 1

所以for循环将是:

for i in range(len(words)-1):

len(words)将返回长度的文字数字计数,但是当迭代范围时,范围从 0 开始,所以你希望你的范围是 len(words) - 1

于 2021-08-26T07:50:45.273 回答
0
len() 

在这种情况下,该函数将输出为 5,因为计数器从 1 而不是 0 开始。因此,如果要遍历列表,请使用:

for i in range(len(words) - 1):

这将计数到最后一个元素,而不是遍历并给出错误。

于 2021-08-26T07:55:42.333 回答