NLTK python 错误:“TypeError: 'dict_keys' 对象不可下标”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26394748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NLTK python error: "TypeError: 'dict_keys' object is not subscriptable"
提问by user3760644
I am following instructions for a class homework assignment and I am supposed to look up the top 200 most frequently used words in a text file.
我正在遵循课堂作业的说明,我应该在文本文件中查找前 200 个最常用的单词。
Here's the last part of the code:
这是代码的最后一部分:
fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab[:200]
But when I press enter after the vocab 200 line, it returns:
但是当我在 vocab 200 行后按 Enter 时,它返回:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dict_keys' object is not subscriptable
Any suggestions on how to fix this so it can correctly return an answer?
关于如何解决此问题以便它可以正确返回答案的任何建议?
采纳答案by Klaus D.
Looks like you are using Python 3. In Python 3 dict.keys()returns an iterable but not indexable object. The most simple (but not so efficient) solution would be:
看起来您正在使用 Python 3。在 Python 3 中dict.keys()返回一个可迭代但不可索引的对象。最简单(但不是那么有效)的解决方案是:
vocab = list(fdist1.keys())
回答by Shikhar Gupta
To print the most frequently used 200 words use: fdist1.most_common(200) The above line of code will return the 200 most frequently used words as key-frequency pair.
要打印最常用的 200 个单词,请使用: fdist1.most_common(200) 上面的代码行将返回 200 个最常用的单词作为键频对。
回答by lasu moses
If your using python 3 try:
如果您使用 python 3,请尝试:
fdist1.most_common(200)
instead, to get the 200 most frequent words.
相反,要获得 200 个最常用的单词。
回答by Roy Chen
I am using python 3.5and I meet the same problem of TypeError.
我正在使用python 3.5,我遇到了同样的问题 TypeError。
Using vocab = list(fdist1.keys())does not give me the top 50 most frequently used words.
But fdist1.most_common(50)does.
Usingvocab = list(fdist1.keys())并没有给我前 50 个最常用的词。
但fdist1.most_common(50)确实如此。
Further,if you just want to show those top 50 words not with their frequency,you can try :
此外,如果您只想显示前 50 个单词而不是它们的频率,您可以尝试:
[word for (word, freq) in fdist1.most_common(50)]
[word for (word, freq) in fdist1.most_common(50)]
回答by Heron
fdist1 = FreqDist(NSmyText)
fdist1 = FreqDist(NSmyText)
vocab=fdist1.keys()
vocab=fdist1.keys()
This code is using in Python2.7. So you should do some change. dic.keys() returns an iteratable. So using:
此代码在 Python2.7 中使用。所以你应该做一些改变。dic.keys() 返回一个可迭代对象。所以使用:
list(fdist1.keys())
list(fdist1.keys())

