简体   繁体   English

如何将nltk.corpus中的单词与索引一起使用?

[英]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? 如果我想从words.words()中获得第1252个单词,我该怎么做? 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. NLTK中的words.words()应该是一个列表。 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] 因此,如果您想在列表中获得第1252个单词(假设您是用Python进行计数,那么第1个位置从0开始),只需执行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 如果您需要一次访问该列表中的许多单词(例如,从索引1、20、500提取项目),我建议使用Python的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') 如果要获取该words.words()列表中某个单词的索引,只需执行words.words().index('word_you_want_index_for')

thanks @Padraic Cunningham for the reminder on python-indexing 感谢@Padraic Cunningham对python-indexing的提醒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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