Python 类型错误:列表索引必须是整数,而不是 str(实际上是布尔转换)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38737955/
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
TypeError: list indices must be integers, not str (boolean convertion actually)
提问by RokiDGupta
import nltk
import random
from nltk.corpus import movie_reviews
documents=[(list(movie_reviews.words(fileid)),category)
for category in movie_reviews.categories()
for fileid in movie_reviews.fileids(category)]
random.shuffle(documents)
#print(documents[1])
all_words=[]
for w in movie_reviews.words():
all_words.append(w.lower())
all_words=nltk.FreqDist(all_words)
word_features = list(all_words.keys())[:3000]
def find_features(document):
words = set(document)
features=[]
for w in word_features:
features[w]= (w in words)
return features
print((find_features(movie_reviews.words('neg/cv000_29416.txt'))))
featuresets = [(find_features(rev), category) for (rev,category) in documents]
After run, I am getting the error
运行后,我收到错误
features[w]= (w in words)
TypeError: list indices must be integers, not str
Please help me to solve it...
请帮我解决它...
回答by Nickil Maveli
Only change that needs to be made is that features
must be initialized to a dict
({}
) rather than a list
([]
) and then you could populate it's contents.
唯一需要进行的更改是features
必须将其初始化为 a dict
( {}
) 而不是 a list
( []
) 然后您可以填充它的内容。
The TypeError
was because word_features
is a list of stringswhich you were trying to index using a list and lists can't have string indices.
这TypeError
是因为word_features
是您尝试使用列表索引的字符串列表,并且列表不能具有字符串索引。
features={}
for w in word_features:
features[w] = (w in words)
Here, the elements present in word_features
constitute the keys
of dictionary, features
holding boolean values, True
based on whether the same element appears in words
(which holds unique items due to calling of set()
) and False
for the vice-versa situation.
这里,存在于的元素word_features
构成了keys
of 字典,features
保存布尔值,True
基于相同的元素是否出现在words
(由于调用而保存唯一项set()
),False
反之亦然。
回答by Raja Sattiraju
You have tried to index a list features
with a string and it is not possible with python. List indices can only be integers. What you need is a dictionary
.
您试图features
用字符串索引一个列表,但用 python 是不可能的。列表索引只能是整数。你需要的是一个dictionary
.
Try using a defaultdict
meaning that even if a key is not found in the dictionary, instead of a KeyError
being thrown, a new entry is created
尝试使用一种defaultdict
含义,即使在字典中找不到键,也不会KeyError
抛出一个新条目,而是创建一个新条目
from collections import defaultdict
features = defaultdict()
for w in word_features:
features[w] = [w in words]