Oscar Johansson Oscar Johansson - 8 months ago 32
Python Question

How do you use index with words from nltk.corpus?

If I were to want to get the 1252nd word from words.words() how would I do it? Of course I could do something like this, but it's so ugly I can barely look at it.

random_word = 1252
counter = 0
for i in words.words():
if counter == random_word:
counter += 1

Is there another way?


words.words() from NLTK should be a list. With lists you can just do indexing.

So if you'd like to get the 1252nd word in the list (assuming you're counting pythonically, so 1st position starts at 0), just do words.words()[1251]

If you need to access many words from that list at one time (e.g. pull out items at index 1, 20, 500), I would suggest using Python's itemgetter

If you wanted to get the index of a certain word in that words.words() list, just do words.words().index('word_you_want_index_for')

thanks @Padraic Cunningham for the reminder on python-indexing