gpt4 book ai didi

python - NLTK python 错误 : "TypeError: ' dict_keys' object is not subscriptable"

转载 作者:IT老高 更新时间:2023-10-28 22:17:45 26 4
gpt4 key购买 nike

我正在按照类作业的说明进行操作,并且我应该在文本文件中查找最常用的 200 个单词。

这是代码的最后一部分:

fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab[:200]

但是当我在 vocab 200 行之后按 enter 时,它会返回:

 Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object is not subscriptable

有关如何解决此问题以便正确返回答案的任何建议?

最佳答案

看起来您使用的是 Python 3。在 Python 3 中,dict.keys() 返回一个可迭代但不可索引的对象。最简单(但不是那么有效)的解决方案是:

vocab = list(fdist1.keys())[:200]

在某些情况下,希望继续使用迭代器对象而不是列表。这可以通过 itertools.islice() 来完成:

import itertools
vocal_iterator = itertools.islice(fdist1.keys(), 200)

关于python - NLTK python 错误 : "TypeError: ' dict_keys' object is not subscriptable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26394748/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com