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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:21:55  来源:igfitidea点击:

TypeError: list indices must be integers, not str (boolean convertion actually)

pythonfindmoviereview

提问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 featuresmust be initialized to a dict({}) rather than a list([]) and then you could populate it's contents.

唯一需要进行的更改是features必须将其初始化为 a dict( {}) 而不是 a list( []) 然后您可以填充它的内容。

The TypeErrorwas because word_featuresis 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_featuresconstitute the keysof dictionary, featuresholding boolean values, Truebased on whether the same element appears in words(which holds unique items due to calling of set()) and Falsefor the vice-versa situation.

这里,存在于的元素word_features构成了keysof 字典,features保存布尔值,True基于相同的元素是否出现在words(由于调用而保存唯一项set()),False反之亦然。

回答by Raja Sattiraju

You have tried to index a list featureswith 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 defaultdictmeaning that even if a key is not found in the dictionary, instead of a KeyErrorbeing thrown, a new entry is created

尝试使用一种defaultdict含义,即使在字典中找不到键,也不会KeyError抛出一个新条目,而是创建一个新条目

from collections import defaultdict

features = defaultdict()
for w in word_features:
    features[w] = [w in words]