TypeError: индексы списка должны быть целыми и срезом, а не Str при использовании вложенных словарейPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 TypeError: индексы списка должны быть целыми и срезом, а не Str при использовании вложенных словарей

Сообщение Anonymous »

Я создаю инвертированный индекс текстовых файлов, хранящихся локально с использованием вложенных словарей. Абстрактная структура инвертированного индекса ниже (значения являются целочисленными числами). В любом значении слов ключа '0' является IDF, а значение ключа '1' - TF. < /P>

Код: Выделить всё

inverted_index={'word1':{'0':idf_value, '1': 2 , 'filename1': frequency_value, 'filename2': frequency_value},'word2':{'0':idf_value, '1': 2, 'filename1': frequency_value, 'filename2': frequency_value}}
< /code>
И это код: < /p>
import textract, math, os
docs=[]
#Read the files and store them in docs
folder = os.listdir("./input/")
for file in folder:
if file.endswith("txt"):
docs.append ([file,textract.process("./input/"+file)])

inverted_index={}
for doc in docs:
words=doc[1].decode()
words=words.split(" ")

#loop through and build the inverted index
for word in words:
temp={}
#to remove initial white space
if (word == " ") or (word==""):
continue
if word not in inverted_index:
temp[doc[0]]=1
temp['0']=0 #idf
temp['1']=1 #tf
inverted_index[word]=temp
else:
if doc[0] not in inverted_index[word].keys():
inverted_index[word][doc[0]]=1
inverted_index[word]['1']=inverted_index[word]['1']+1
else:
inverted_index[word][doc[0]]=inverted_index[word][doc[0]]+1

# to sort and print values with calculating the the tf and idf on the fly
for key, value in sorted(inverted_index.items()): # to sort words alphabitically
inverted_index[key]=sorted(inverted_index[key]) # to sort the filenames where the word occured.
inverted_index[key]['0']=math.log2(len(docs)/value['1']) # the error in this line
print(key, value)
< /code>
Но я получаю эту ошибку во второй последней строке: < /p>
Traceback (most recent call last):
File "aaaa.py", line 34, in 
inverted_index[key]['0']=math.log2(len(docs)/value['1'])
TypeError: list indices must be integers or slices, not str
Как я могу исправить эту ошибку?


Подробнее здесь: https://stackoverflow.com/questions/472 ... -nested-di
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»