Home > Mobile >  IndexError: list index out of range in VSCode but works well in colabs
IndexError: list index out of range in VSCode but works well in colabs

Time:12-09

I'm trying to learn entailments in wordnet by rewriting code from a book. The code works well when I code it in colabs, but when I move it in VSCode, I receive an error message:IndexError: list index out of range

The code is like this:

for action in ['walk', 'eat', 'digest']:
  action_syn=wn.synsets(action, pos='v')[0]
  print(action_syn, '-->', action_syn.entailments())

with problem indicates in here: action_syn=wn.synsets(action, pos='v')[0]

Can you please explain to me why this happens and how to resolve it. Thank you.

CodePudding user response:

list index out of range in wn.synsets(action, pos='v')[0] would mean that there is no element [0]. Which means wn.synsets() has returned an empty list.

If you want the code to be more sturdy, check the list length before using it:

synset = wn.sysets(action,pos='v')
if len(myList)==0:
  print("Not found")
else:
  action_syn = synset[0]
  #...your other code

Of course you should be finding entries for "walk" as a verb, so I'd guess wordnet was installed correctly on colab and has not been installed correctly on your local machine (or wherever you are running vscode). I'd start that troubleshooting here: https://www.nltk.org/install.html

CodePudding user response:

Thank you for the insight, Darren. However, the problem is not on the list ['walk', 'eat', 'digest'] but in the filtered synsets (I only want to get synsets with pos='verb wn.synsets(action, pos='v')[0].

The problem was resolved when I did one-by-one process like this:

`for action in ['walk', 'eat', 'digest']:
        action_syn=wn.synsets(action)[0]
        if action_syn.pos()=='v'
            syn_word_list.append(action_syn)    
        syn_word_list.append(action_syn)`

However, I don't know how to make it efficient and free from error.

  • Related