Я создаю инвертированный индекс текстовых файлов, хранящихся локально с использованием вложенных словарей. Абстрактная структура инвертированного индекса ниже (значения являются целочисленными числами). В любом значении слов ключа '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
Я создаю инвертированный индекс текстовых файлов, хранящихся локально с использованием вложенных словарей. Абстрактная структура инвертированного индекса ниже (значения являются целочисленными числами). В любом значении слов ключа '0' является IDF, а значение ключа '1' - TF. < /P> [code]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 [/code] Как я могу исправить эту ошибку?
Я относительно новичок в Python, и я пытаюсь настроить сценарий, который будет читать файл JSON, который я импортирую из API, а затем написать этот файл в файл паркета.
В этом файле json у меня есть поля с такими списками, как адреса электронной...
Я относительно новичок в Python, и я пытаюсь настроить сценарий, который будет читать файл JSON, который я импортирую из API, а затем написать этот файл в файл паркета.
В этом файле json у меня есть поля с такими списками, как адреса электронной...
Мне хотелось бы понять, почему это работает нормально:
>>> test_string = 'long brown fox jump over a lazy python'
>>> 'formatted {test_string } '.format(test_string=test_string)
'formatted l '
Однако это не удается:
>>> 'formatted {test_string }...
Мне хотелось бы понять, почему это работает нормально:
>>> test_string = 'long brown fox jump over a lazy python'
>>> 'formatted {test_string } '.format(test_string=test_string)
'formatted l '
Однако это не удается:
>>> 'formatted {test_string }...
Это распространенный вопрос по SO, но все примеры, которые я рассмотрел, довольно сложны. Поэтому я публикую самый простой пример, который только могу придумать, чтобы получить прямой ответ.
x =
print(x )
(1,2)
print(x )
TypeError: list indices...