简体   繁体   中英

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:
            print(i)
        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 (eg 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM